Home > Web Front-end > JS Tutorial > body text

How to Find Common Elements in Multiple JavaScript Arrays?

Barbara Streisand
Release: 2024-10-24 16:42:02
Original
720 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!