Home > Net >  method to check if a specific number with a group of numbers exists within an array in javascript
method to check if a specific number with a group of numbers exists within an array in javascript

Time:02-17

var numbers = [1, 2, 3, 4, 5, 6, 7, 8];

need to check if 2, 3, 4 exist in the array. Only has to be 1 of these numbers to return true...not all. What's the best approach. I was thinking lodash includes, but I believe I can only pass in a single value.

CodePudding user response:

Using Array#some and Array#includes:

const hasAny = (arr = [], nums = []) =>
  nums.some(n => arr.includes(n));

console.log( hasAny([1, 2, 3, 4, 5, 6, 7, 8], [2, 3, 4]) );

CodePudding user response:

If you want to get the intersection, you can filter the first array by the second array, or rather, whether or not the second array contains each element of the first. You can see which members were included, or check the size of the new array > 0 if you need a boolean (or use Mr Badawi's .some method).

var numbers = [1, 2, 3, 4, 5, 6, 7, 8];
var needs = [2, 3, 4 ];

var check = numbers.filter(x=>needs.includes(x));
console.log(check);

var numbers = [3, 5, 6, 7, 8, 12, 20];
var needs = [2, 3, 4 ];

var check = numbers.filter(x=>needs.includes(x));
console.log(check);

  • Related