I’m seeking assistance on how to locate specific elements in a JavaScript array that contains objects. I’ve been having a tough time figuring this out.
I would like to search for matches based on selections made by the users. I attempted to implement a function, but it hasn’t worked:
var selectedElementOne = $("#board img:first-child").attr('id');
var selectedElementTwo = $("#board img:last-child").attr('id');
function findCombo(element) {
return elementDefinitions.element === selectedElementOne;
}
I also tried using a for loop:
for (var i = 0; i < elementDefinitions.length; i++) {
var currentElement = elementDefinitions[i].element;
var matchIndex = currentElement.indexOf(selectedElementOne);
console.log(matchIndex);
}
I’m not sure what I’m doing wrong. How can I properly traverse this array structure to retrieve the required element?
Your findCombo function has a syntax issue. You’re using elementDefinitions.element but elementDefinitions is an array, not an object - so there’s no element property to access directly. Use the filter method instead: elementDefinitions.filter(item => item.element === selectedElementOne) returns all matches, or use find() for just the first one. Your for loop idea was actually right, but indexOf looks for substrings in strings - you need exact property matching here. Once you grab the correct element object, you can access its combos property and check if your second selected element exists as a key.
hey, you got the right idea but i think your findCombo function could be better. try using elementDefinitions.find(el => el.element === selectedElementOne) to get the whole object. indexOf isn’t the way to go here since you need exact matches, not substring searches.
Your function isn’t filtering the array - that’s the issue. I ran into the same problem and found Array.prototype.some() works great for checking if something exists, while find() grabs the actual object. Your for loop idea was solid, but ditch the indexOf stuff. Just compare properties directly: currentElement === selectedElementOne. Once you’ve got the right element object, check if elementObject.combos[selectedElementTwo] exists to get your combination result. Think of each array item as a whole object instead of searching through strings.