2

I have an array of arrays, and I would like to iterate this array with the values of another array looking for a match.

let arr1 = [[1,3,5],[2,4,7],[1,5,9]] // [false, false, true]
let arr2 = [1,2,4,5,9] // arr2 contains all values of arr1[2]. return true.

I need it to return truthy falsey if all values in an arr1[i] are present in arr2

for (let i = 0; i < arr1.length; i++) {
  if (arr2.every(arr1[i])) {
    return true
  }
}
0

2 Answers 2

2

You can use .map() with .every()

let arr1 = [[1,3,5],[2,4,7],[1,5,9]];
let arr2 = [1,2,4,5,9];
let result = arr1.map(x => x.every(y => arr2.includes(y)));
console.log(result);

or .filter() if you just want to get matching results:

let arr1 = [[1,3,5],[2,4,7],[1,5,9]];
let arr2 = [1,2,4,5,9];
let result = arr1.filter(x => x.every(y => arr2.includes(y)));
console.log(result);

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

2 Comments

Should technically use a filter over a map - map should always return the same amount of elements in the array it maps over.
@tymeJV included .filter() in my answer
1

You could use Array#some for a single boolean value by using Array#every for each inner array and check array2 with Array#includes.

var array1 = [[1, 3, 5], [2, 4, 7], [1, 5, 9]],
    array2 = [1, 2, 4, 5, 9],
    result = array1.some(a => a.every(v => array2.includes(v)));
    
console.log(result);

Using a Set.

var array1 = [[1, 3, 5], [2, 4, 7], [1, 5, 9]],
    array2 = [1, 2, 4, 5, 9],
    result = array1.some((s => a => a.every(v => s.has(v)))(new Set(array2)));
    
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.