Utilize the every
and some
methods to compare the arrays with each other.
If you desire an array containing the subarrays that match, employ the filter
method:
let result = small.filter(arr =>
large.some(otherArr =>
otherArr.length === arr.length && otherArr.every((item, i) => item === arr[i])
)
);
This code snippet filters out the subarray from small
that has a matching subarray in large
with the same length and elements/items.
Live Example:
let small = [[1, 3], [2, 2], [2, 3], [3, 0]];
let large = [[1, 0], [1, 1], [2, 0], [2, 2], [2, 5], [3, 0], [3, 2]];
let result = small.filter(arr =>
large.some(otherArr =>
otherArr.length === arr.length && otherArr.every((item, i) => item === arr[i])
)
);
console.log(result);
If you just need a count, then utilize the reduce
method instead of filter
for counting the matched items (based on the fact that the numeric value of true
is 1
and that of false
is 0
):
let count = small.reduce((counter, arr) =>
counter + large.some(otherArr =>
otherArr.length === arr.length && otherArr.every((item, i) => item === arr[i])
)
, 0);
Live Example:
let small = [[1, 3], [2, 2], [2, 3], [3, 0]];
let large = [[1, 0], [1, 1], [2, 0], [2, 2], [2, 5], [3, 0], [3, 2]];
let count = small.reduce((counter, arr) =>
counter + large.some(otherArr =>
otherArr.length === arr.length && otherArr.every((item, i) => item === arr[i])
)
, 0);
console.log(count);
Note: If the subarrays consist solely of numbers, you could simplify the code by using Array#toString
instead of comparing each element and the length:
let result = small.filter(arr => large.some(otherArr => "" + otherArr === "" + arr));
This approach converts both arrays into strings and compares the two strings directly. It can be implemented with reduce
as well.