1

In Javascript, how can I ensure that the array of ages has both ages 10 and 18 and not just one.

var ages = [3, 10, 18, 20];
ages.filter(age => age === 10 || age === 18); // returns 10 and 18
ages.filter(age => age === 10 && age === 18); // returns null

The && doesn't ensure that both exist, as it returns null. I know I can use 2 different ages.find/filter and check the combined result, but I am wondering if there is a more elegant way of doing this in a single statement.

To clarify, in the ages array, if I check for 10 (exists) and 21 (doesn't exist), it should return null or false, as one of them does not exist.

5
  • 1
    new Set(ages.filter(age => age === 10 || age === 18)).size >= 2 Commented Jan 21, 2017 at 17:23
  • See Array.includes Commented Jan 21, 2017 at 17:23
  • I think its best to use 2 different filters since in an iteration, age can just be a single number, either 10 or 18 so if you use &&, one of them will always be false. Commented Jan 21, 2017 at 17:26
  • @SpencerWieczorek not a duplicate, I am trying to ensure both exist at once, not just one... Commented Jan 21, 2017 at 17:31
  • Checking for two is just checking for a single one twice. This is a duplicate in the same way finding element a and element b is a duplicate for finding element a. So other than just if ( ages.indexOf( 10 ) > -1 ) it's just if ( ages.indexOf( 10 ) > -1 && ages .indexOf( 18 ) > -1). That's why it's a duplicate. Commented Jan 21, 2017 at 19:13

1 Answer 1

5

You have to use includes function:

var ages = [3, 10, 18, 20];
console.log(ages.includes(10) && ages.includes(18));

Another method is to use indexOf method:

arr.indexOf(searchElement)

arr.indexOf(searchElement, fromIndex)

var ages = [3, 10, 18, 20];
console.log(ages.indexOf(10)!=-1 && ages.indexOf(18)!=-1);

findIndex is another method that you can use.It actions like indexOf, but there are some differences:

Array.prototype.indexOf() expects a value as parameter. This is usefull for arrays of primitive types,such as Number, String, Boolean.

Array.prototype.findIndex() have a callback function as first parameter. This is usefull specially when you have array of objects.

var ages = [3, 10, 18, 20];
var bool=ages.findIndex(a=>a==10)!=-1 && ages.findIndex(a=>a==18)!=-1;
console.log(bool);

Sign up to request clarification or add additional context in comments.

3 Comments

works like a charm, thanks for including both ways :)
instead of using findIndex() != -1 I'd rather use some(). ages.some(v => v === 10) && ages.some(v => v === 18)
Image
Thanks for your point ! You can include sugestion inside my answer if you wish.Good point.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.