DEV Community

Discussion on: Need help understanding: Filtering an array of objects in Javascript

Collapse
 
dmfay profile image
Dian Fay

includes returns a boolean value but forEach does not (or rather, it returns undefined). So the result of the includes call is simply thrown away if you use forEach instead of some.

Two obvious improvements to the working method:

  • iterate restaurant.menuEntities with some as well, if it's possible that the result you're looking for is not in the very first one
  • use reduce instead of filter; if you search, there have been numerous guides posted here

Additionally, if you're retrieving the restaurant & menu records from a relational database you could short-circuit the whole thing by filtering in your query instead of in application logic.

Collapse
 
leanminmachine profile image
leanminmachine

Hahhaa for the menuEntities yeah I'll definitely have to use .some if there's more than one.. Thanks for the reminder & explanation, makes sense that the results of includes is thrown away with forEach