Home > Article > Web Front-end > How to Find Matches in Arrays Across Multiple Arrays in Javascript?
Finding Matches in Arrays across Different Arrays
Consider a scenario where you have multiple JavaScript arrays with string values, and you need to find and extract only the matches that are identical in every single array.
Imagine you have the following arrays:
var arr1 = ['apple', 'orange', 'banana', 'pear', 'fish', 'pancake', 'taco', 'pizza']; var arr2 = ['taco', 'fish', 'apple', 'pizza']; var arr3 = ['banana', 'pizza', 'fish', 'apple'];
Your goal is to obtain an array containing only the matches that appear in all three arrays, which would be:
['apple', 'fish', 'pizza']
This task can be accomplished without the use of external libraries. One approach involves using the filter() method in combination with every().
var result = arrays.shift().filter(function(v) { return arrays.every(function(a) { return a.indexOf(v) !== -1; }); });
In this solution:
Sorting the outer array (arrays) based on length can optimize performance.
arrays.sort(function(a, b) { return a.length - b.length; });
Additionally, if duplicates are present in the arrays, you can use the reduce() method instead of filter().
var result = arrays.shift().reduce(function(res, v) { if (res.indexOf(v) === -1 && arrays.every(function(a) { return a.indexOf(v) !== -1; })) res.push(v); return res; }, []);
By using these methods, you can effectively find matches in arrays across multiple arrays, even if they contain unknown lengths or duplicates.
The above is the detailed content of How to Find Matches in Arrays Across Multiple Arrays in Javascript?. For more information, please follow other related articles on the PHP Chinese website!