Given multiple JavaScript arrays of string values, find the elements that occur identically in all the arrays. For example:
<code class="javascript">var arr1 = ['apple', 'orange', 'banana', 'pear', 'fish', 'pancake', 'taco', 'pizza']; var arr2 = ['taco', 'fish', 'apple', 'pizza']; var arr3 = ['banana', 'pizza', 'fish', 'apple'];</code>
Expected output:
<code class="javascript">['apple', 'fish', 'pizza']</code>
To find the matching elements, we can use a combination of Array methods:
<code class="javascript">const arrays = [arr1, arr2, arr3]; const result = arrays.shift().filter((v) => { return arrays.every((a) => { return a.indexOf(v) !== -1; }); });</code>
Steps:
By iteratively applying this logic to each array, we can effectively find the elements that occur identically in all the provided arrays.
Duplicate Element Handling:
The provided solution assumes that the arrays do not contain duplicate elements. If they do, you can modify the code as follows:
<code class="javascript">const result = arrays.shift().reduce((res, v) => { if (res.indexOf(v) === -1 && arrays.every((a) => { return a.indexOf(v) !== -1; })) res.push(v); return res; }, []);</code>
This code uses .reduce() instead of .filter(). It checks for duplicates within the result array and only adds unique elements that are present in every array.
Arbitrary Number of Arrays:
The solution is designed to work with an unknown number of arrays. By using arrays.shift(), we can sequentially compare the first array to the remaining arrays until all arrays have been processed.
The above is the detailed content of How to Find Matching Elements Across Multiple JavaScript Arrays?. For more information, please follow other related articles on the PHP Chinese website!