Finding matches between multiple JavaScript Arrays
Posted
by
Chris Barr
on Stack Overflow
See other posts from Stack Overflow
or by Chris Barr
Published on 2012-06-18T01:23:45Z
Indexed on
2012/06/18
3:16 UTC
Read the original article
Hit count: 273
I have multiple arrays with string values and I want to compare them and only keep the matching results that are identical between ALL of them.
Given this example code:
var arr1 = ['apple', 'orange', 'banana', 'pear', 'fish', 'pancake', 'taco', 'pizza'];
var arr2 = ['taco', 'fish', 'apple', 'pizza'];
var arr3 = ['banana', 'pizza', 'fish', 'apple'];
I would like to to produce the following array that contains matches from all given arrays:
['apple', 'fish', 'pizza']
I know I can combine all the arrays with var newArr = arr1.concat(arr2, arr3);
but that just give me an array with everything, plus the duplicates. Can this be done easily without needing the overhead of libraries such as underscore.js?
(Great, and now i'm hungry too!)
EDIT I suppose I should mention that there could be an unknown amount of arrays, I was just using 3 as an example.
© Stack Overflow or respective owner