Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
65
rated 0 times [  72] [ 7]  / answers: 1 / hits: 74930  / 12 Years ago, mon, june 18, 2012, 12:00:00

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.


More From » jquery

 Answers
49
var result = arrays.shift().filter(function(v) {
return arrays.every(function(a) {
return a.indexOf(v) !== -1;
});
});


DEMO: http://jsfiddle.net/nWjcp/2/



You could first sort the outer Array to get the shortest Array at the beginning...



arrays.sort(function(a, b) {
return a.length - b.length;
});





For completeness, here's a solution that deals with duplicates in the Arrays. It uses .reduce() instead of .filter()...



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;
}, []);


DEMO: http://jsfiddle.net/nWjcp/4/


[#84844] Friday, June 15, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mireyag

Total Points: 73
Total Questions: 107
Total Answers: 85

Location: Ukraine
Member since Sun, Dec 13, 2020
3 Years ago
mireyag questions
Sun, Aug 15, 21, 00:00, 3 Years ago
Wed, Dec 16, 20, 00:00, 3 Years ago
Tue, Sep 1, 20, 00:00, 4 Years ago
Sun, Jul 5, 20, 00:00, 4 Years ago
;