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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With