Let's say I have one array with subarrays and another array like this:
var arr1 = [[1,2], [3,4], [5,6]];
var arr2 = [3,4];
I want to print all of the subarrays from arr1
that contain every element of arr2
. But since this is just one example of what I want, I also want to be able to apply this to any set of arrays that sort of look like this.
How would I create a for-loop that can test if each arr1[i]
contains all elements of arr2
? So far I have this code, but it only checks if a single element matches an element in each subarray. I've been trying to look up ways to change this to make the function I need, but I'm drawing a blank on solutions.
var newArr = [];
for (var j = 0; j < arr1.length; j++) {
if (arr1[i].hasOwnProperty(arr2[j])) {
newArr.splice(-1, 0, arr1[i]);
}
}
return newArr;
Use Array#filter
to iterate the arr1
, and remove sub arrays if they don't pass the Array#every
test - check that every item in arr2
is in the sub array using Array#indexOf
(or Array#includes
if supported).
var arr1 = [[1,2], [3,4], [5,6], [1, 3, 6, 4]]; var arr2 = [3,4]; var result = arr1.filter(function(sub) { return arr2.every(function(n) { return sub.indexOf(n) !== -1; // or sub.includes(n) }); }); console.log(result);
I would do as follows;
var arr1 = [[1,2], [3,4], [5,6]], arr2 = [3,4]; res = arr1.filter(sa => sa.every(n => arr2.includes(n))); console.log(res);
Wow there is a very similar answer.. Then lets do it with a .reduce()
var arr1 = [[1,2], [3,4], [5,6]], arr2 = [3,4,5,6]; res = arr1.reduce((r,s) => s.every(n => arr2.includes(n)) ? r.concat(s):r,[]); console.log(res);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.