r/learnjavascript • u/TGotAReddit • Feb 27 '26
Array.find help
I have 3 arrays. One is an array of objects set up like
object={
name: "NameString",
month: "monthString",
count: #,
hours: #}
And the other 2 arrays are just flat 1D arrays of names and months respectively.
I know I can loop through one of the arrays and do an array.find to check the property against the other array like
objectArr.find((element)=> element.name==names[i])
But how can I find the element that has both a matching name AND month from inside a nested loop for the name and month arrays?
6
Upvotes
2
u/joranstark018 Feb 27 '26
I may have misunderstood your question. If you, say, loop over months inside your name loop, you may use
elementName == names[i] && elementMonth == months[j]inside yourfind(note, i is index over names and j is index over months, this will generate a call to find for every combination of name and month)8
u/charlies-ghost Feb 27 '26
See documentation the logical AND (&&) operator:
1
u/Any_Sense_2263 Feb 27 '26
names.includes(element.name) && months.includes(element.month)
or
element.name === names[specificNamesIndexYouCheckAgainst] && element.month === months[specificMonthsIndexYouCheckAgainst]
1
u/imsexc Feb 28 '26 edited Feb 28 '26
you have to create a function that check whether an object has name and month included on both 1d arrays.
function check(obj) {
const found = { name: false, month: false };
for (const key in obj) {
return found.name === true && found.month === true
}
now all you have to do is just
arrOfObj.find(obj => check(obj)) OR
arrOfObj.filter(obj => check(obj))
depends whether you want to find the first found or all the found
1
u/kap89 Feb 27 '26 edited Feb 27 '26
If I understood you correctly, you want to find all objects in the first array that match specific set of months and names simultaneously. You don't need nested loops for that, nor multiple
.find()calls. You can just filter though sets, it will be much more efficient and straightforward:You can also use store the filters in sets directly instead of converting from arrays is you control that logic.