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);
or statements :)This is an experimental technology, part of the ECMAScript 2016 (ES7) proposal. Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.You can make use of the filter method which returns the elements which matches the predicate.The filter() method creates a new array with all elements that pass the test implemented by the provided function.
The find method returns the first element in the array that satisfies the condition. So, using find, you wouldn't be able to return more than 1 element.
Also, the comparison is wrong in your code,
instead of age === (10 || 18)
use age === 10 || age === 18)
var ages = [3, 10, 18, 20];
var result = ages.filter(age => age === 10 || age === 18);
console.log(result);
First,
age === (10 || 18)
is wrong (it checks only age === 10), you need
age === 10 || age === 18
for checking, second use Array#filter to get an array with the result.
var ages = [3, 10, 18, 20];
console.log(ages.filter(age => age === 10 || age === 18));
You can't. At least not with just one call.
(emphasis mine)
The find() method returns a value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
A better way of approaching this would be to use filter.
var ages = [3, 10, 18, 20];
console.log(ages.filter(age => age === 10 || age === 18));
The accepted answers are fine, but they are slow if the arrays are big.
If you only need to find the first 2 items that match, you can use this solution:
let a = null, b = null;
for (let age of ages) {
if (age === 10) {
a = age
}
else if(age === 18){
b = age
}
if(a != null && b != null){
break;
}
}
In the worst case, it will iterate the ages array entirely once.
age === 10 || age === 18filter()is the way to go then. Be aware that if no result is found, you'll get an empty Array instead ofundefined. So you can check its.lengthto see if it contains any matches.