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 && 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!