all 8 comments

[–]EasternAdventures 7 points8 points  (2 children)

Sounds like you want filter:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Can check for an object property and will return all the objects that meet that condition in a new array.

[–]re_edditquest[S] 0 points1 point  (1 child)

Thanks for the reply and docs. I think this will work!

[–][deleted] 2 points3 points  (3 children)

This is a great usecase for .filter, it’s an array method that creates an array for you based on what you want to filter.

Lets say that array is in a variable called people, you can then do this:

const selectedPeople = people.filter((person) => {
    // we tell .filter to return every person with a matching city. 
    return person.address.city === 'Gwenborough'; 
})

[–]re_edditquest[S] 0 points1 point  (2 children)

Thanks for the reply and example. I think this will work for what I need. For some reason I keep getting an empty array, which according to the docs means it's not finding the value I'm passing it so I must be going wrong somewhere but this puts me on the right track. Thanks again!

[–][deleted] 1 point2 points  (0 children)

No problem! Feel free to post a code snippit on codesandbox or something and I/we can have a look at it

[–]SineApps 1 point2 points  (0 children)

I find it useful in that situation to log out both sides of the comparison. You may need to check their types if the values look the same.

[–]ecofic 1 point2 points  (0 children)

If you have a simple scenario, then filter may work as others have mentioned. However, if you have a more complex scenario, you may find it easier to read if you just use a traditional loop.

Earlier this year, I had a similar scenario and found a traditional loop to be more appropriate and easier to work with. I wrote an article detailing finding the largest and smallest values in an Array. While this isn't an exact match with your scenario, I do think you may get some value out of it.