Reputation: 8674
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
Upvotes: 2
Views: 1722
Reputation: 2070
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.
Upvotes: 0
Reputation: 18888
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);
Upvotes: 5
Reputation: 9878
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);
Upvotes: 5
Reputation: 386550
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));
Upvotes: 2
Reputation: 32511
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));
Upvotes: 1