Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Find 2 items in array?

Using find in Javascript, how can I find 2 items 10 and 18 from the array?

var ages = [3, 10, 18, 20];
ages.find(age => age === 10); // works on one item, returns 10
ages.find(age => age === (10 || 18)); // does not return 10 and 18
like image 524
Wonka Avatar asked Nov 25 '25 12:11

Wonka


1 Answers

I would create another array that holds the possible ages you are looking for. This is going to be easier to read and maintain than or statements.

var ages = [3, 10, 18, 20];
var criteria = [10, 18];

let found = ages.filter(age => criteria.includes(age));
console.log(found);

As pointed out by @Flavio Ochoa, Array.includes may not be supported in legacy browsers. If you're worried about support, or are not using a polyfill for Array.includes, you can just use Array.indexOf instead:

ages.filter(age => criteria.indexOf(age) > -1);
like image 139
KevBot Avatar answered Nov 28 '25 01:11

KevBot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!