Home  >  Article  >  Web Front-end  >  How to Find Matches in Arrays Across Multiple Arrays in Javascript?

How to Find Matches in Arrays Across Multiple Arrays in Javascript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 01:58:29712browse

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:

  • shift() removes the first array from the arrays collection.
  • filter() creates a new array containing only the elements that pass a specified condition.
  • every() checks whether all elements in the arrays collection pass a condition.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn