Home  >  Article  >  Web Front-end  >  How to Find Common Elements in Multiple JavaScript Arrays?

How to Find Common Elements in Multiple JavaScript Arrays?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 16:42:02721browse

How to Find Common Elements in Multiple JavaScript Arrays?

Finding Matches Between Multiple JavaScript Arrays

Question:

How can you compare multiple JavaScript arrays containing string values and extract only the matches that are identical across all arrays?

Answer:

Utilize the following code snippet for exact matches:

<code class="js">var result = arrays.shift().filter(function(v) {
    return arrays.every(function(a) {
        return a.indexOf(v) !== -1;
    });
});</code>

This implementation traverses each element in the first array, checks whether it exists in all other arrays using indexOf, and conditionally adds it to the result array. Note that it assumes no duplicates exist in any of the input arrays.

If you need to handle duplicates within the input arrays, use the following code:

<code class="js">var result = arrays.shift().reduce(function(res, v) {
    if (res.indexOf(v) === -1 &amp;&amp; arrays.every(function(a) {
        return a.indexOf(v) !== -1;
    })) res.push(v);
    return res;
}, []);</code>

This version uses the reduce method to accumulate matching elements across arrays. Duplicates are filtered out by checking the indexOf in the result array.

The above is the detailed content of How to Find Common Elements in Multiple JavaScript Arrays?. 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