144

I have two arrays, and I want to be able to compare the two and only return the values that match. For example both arrays have the value cat so that is what will be returned. I haven't found anything like this. What would be the best way to return similarities?

var array1 = ["cat", "sum","fun", "run"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];

//if value in array1 is equal to value in array2 then return match: cat
1

13 Answers 13

458

You can use :

const intersection = array1.filter(element => array2.includes(element));
8
  • 20
    This looks like the simplest and most concise answer. Not sure why it's not marked as being the right one. Aug 15, 2018 at 11:56
  • 3
    That is because not all browsers will support it, unless you use a polyfill: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Oct 1, 2018 at 11:58
  • 1
    As of late April 2019, only IE doesn't provide support.
    – absay
    Apr 23, 2019 at 18:01
  • 6
    const intersection = array1.filter(element => array2.indexOf(element) !== -1); without a polyfill.
    – simmer
    May 8, 2019 at 18:00
  • 9
    @Learner from ES6 you can use Set to filter out duplicated values and spread its values in an array like this : const intersection = [...new Set(array1.filter(element => array2.includes(element)))];
    – jota3
    Oct 17, 2019 at 18:58
64

Naturally, my approach was to loop through the first array once and check the index of each value in the second array. If the index is > -1, then push it onto the returned array.

​Array.prototype.diff = function(arr2) {
    var ret = [];
    for(var i in this) {   
        if(arr2.indexOf(this[i]) > -1){
            ret.push(this[i]);
        }
    }
    return ret;
};

​ My solution doesn't use two loops like others do so it may run a bit faster. If you want to avoid using for..in, you can sort both arrays first to reindex all their values:

Array.prototype.diff = function(arr2) {
    var ret = [];
    this.sort();
    arr2.sort();
    for(var i = 0; i < this.length; i += 1) {
        if(arr2.indexOf(this[i]) > -1){
            ret.push(this[i]);
        }
    }
    return ret;
};

Usage would look like:

var array1 = ["cat", "sum","fun", "run", "hut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];

console.log(array1.diff(array2));

If you have an issue/problem with extending the Array prototype, you could easily change this to a function.

var diff = function(arr, arr2) {

And you'd change anywhere where the func originally said this to arr2.

6
  • 5
    .indexOf() just moves the loop. The method loops through the target array internally. (developer.mozilla.org/en-US/docs/JavaScript/Reference/…) Sep 15, 2012 at 1:16
  • the .indexOf() function is probably faster than looping through all the array like done in the compatibility alternative.
    – jeremy
    Sep 15, 2012 at 1:19
  • Is indexOf() smart enough to use a binary search after the sort? Otherwise, this is O(N^2) since you are essentially doing nested looping due to indexOf() performing a linear scan. Even without that issue, why incur the linearithmic cost of sort when you can do this in linear time using an object as a hash table? Sep 15, 2012 at 1:19
  • I've not heard of any ECMASCript engine that switches to a binary search on sorted arrays. Would be an interesting optimization, including carrying a 'sorted' flag around with the array, but I wonder if there'd be enough call for it. Sep 15, 2012 at 1:22
  • This is a bit late, but looks like the latest Chrome versions at least have much faster indexOf: jsperf.com/jquery-inarray-vs-underscore-indexof/43 Feb 6, 2015 at 19:20
34

I found a slight alteration on what @jota3 suggested worked perfectly for me.

var intersections = array1.filter(e => array2.indexOf(e) !== -1);

Hope this helps!

1
  • 8
    It means you were using a javascript version anterior to ES2016 in which includes() has been added. indexOf() will work with any version.
    – jota3
    Apr 5, 2018 at 10:01
17

This function runs in O(n log(n) + m log(m)) compared to O(n*m) (as seen in the other solutions with loops/indexOf) which can be useful if you are dealing with lots of values.

However, because neither "a" > 1 nor "a" < 1, this only works for elements of the same type.

function intersect_arrays(a, b) {
    var sorted_a = a.concat().sort();
    var sorted_b = b.concat().sort();
    var common = [];
    var a_i = 0;
    var b_i = 0;

    while (a_i < a.length
           && b_i < b.length)
    {
        if (sorted_a[a_i] === sorted_b[b_i]) {
            common.push(sorted_a[a_i]);
            a_i++;
            b_i++;
        }
        else if(sorted_a[a_i] < sorted_b[b_i]) {
            a_i++;
        }
        else {
            b_i++;
        }
    }
    return common;
}

Example:

var array1 = ["cat", "sum", "fun", "hut"], //modified for additional match
    array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];
intersect_arrays(array1, array2);
>> ["cat", "hut"]
2
  • The complexity is actually O(nlogn + mlogm + n + m), you forgot to consider the while loop while calculating.
    – Partha
    Apr 27, 2016 at 19:25
  • @Partha n is subsumed by the faster growing n logn, the same applies for m and m log n.
    – phant0m
    Apr 28, 2016 at 12:13
12

Loop through the second array each time you iterate over an element in the first array, then check for matches.

var array1 = ["cat", "sum", "fun", "run"],
    array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];

function getMatch(a, b) {
    var matches = [];

    for ( var i = 0; i < a.length; i++ ) {
        for ( var e = 0; e < b.length; e++ ) {
            if ( a[i] === b[e] ) matches.push( a[i] );
        }
    }
    return matches;
}

getMatch(array1, array2); // ["cat"]
2
  • this uses the length of array 1 * the length of array 2 amount of loops... 24 loops in this case.
    – jeremy
    Sep 15, 2012 at 1:03
  • 1
    no problem. it works, but its just extremely unnecessary and could potentially take forever to run. you can check out my answer for probably a better 1 loop solution
    – jeremy
    Sep 15, 2012 at 1:12
12
var array1  = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var array3 = array2.filter(function(obj) { 
    return array1.indexOf(obj) !== -1; 
});
4
  • @Mr. 1.0 Please look into this efficient and clean code. Jul 16, 2018 at 10:45
  • You may want to explain the above code.
    – jrenk
    Jul 16, 2018 at 11:01
  • Remove "," from the first line and add ";"
    – Abdullah
    Oct 1, 2018 at 6:21
  • This is the easiest to understand
    – leoncc
    Nov 9, 2019 at 18:20
10

You can use javascript function .find() As it says in MDN, it will return the first value that is true. If such an element is found, find immediately returns the value of that element. Otherwise, find returns undefined.

var array1 = ["cat", "sum", "fun", "run", "cat"];
var array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];

found = array1.find((val, index) => {
  console.log('index', index) // Stops at 0
  return array2.includes(val)
})
console.log(found)

Or use .filter(), which loops through every elements first, then give back the result to you.

var array1 = ["cat", "sum", "fun", "run", "cat"];
var array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];

found = array1.filter((val, index) => {
  console.log('index', index) // Stops at array1.length - 1
  return array2.includes(val)
})
console.log(found)

4

use lodash

GLOBAL.utils = require('lodash')
var arr1 = ['first' , 'second'];
var arr2 = ['second '];

var result = utils.difference(arr1 , arr2);
console.log ( "result :" + result );
3

Libraries like underscore and lodash have a utility method called intersection to find matches in arrays passed in. Take a look at: http://underscorejs.org/#intersection

1
  • Good point @EricLeschinski. I modified my answer.
    – leojh
    Mar 31, 2016 at 21:02
2

Done as a answer so I can do formatting...

This is the the process you need to go through. Looping through an array for the specifics.

create an empty array
loop through array1, element by element. {
  loop through array2, element by element {
    if array1.element == array2.element {
      add to your new array
    }
  }
}
6
  • this uses the length of array 1 * the length of array 2 amount of loops... 24 loops in this case.. it'd be better to just check if the index of the value in array1 is existent in array2 and then only 1 loop would be used. see my answer.
    – jeremy
    Sep 15, 2012 at 1:07
  • I thought about that. .indexOf() still isn't supported everywhere, though it can be monkeypatched in easily enough... and .indexOf(), at least in the Mozilla monkeypatch version (developer.mozilla.org/en-US/docs/JavaScript/Reference/…) still loops. It just moves one of the loops to the indexOf function instead. Sep 15, 2012 at 1:14
  • It's supported in all the major browsers, look at the compatibility table...
    – jeremy
    Sep 15, 2012 at 1:16
  • I'm well aware of where indexOf is, and is not, supported. My primary point is that your solution is still a two-loop solution. One of the loops is just hidden. Sep 15, 2012 at 1:20
  • 1
    True -- but I doubt execution speed is the desired goal here. This is a "Level 101" question, so the OP needs an answer that best describes the entire process without shortcuts. Understanding exactly what is going on is more important. Sep 15, 2012 at 1:25
2

If your values are non-null strings or numbers, you can use an object as a dictionary:

var map = {}, result = [], i;
for (i = 0; i < array1.length; ++i) {
    map[array1[i]] = 1;
}

for (i = 0; i < array2.length; ++i) {
    if (map[array2[i]] === 1) {
        result.push(array2[i]);

        // avoid returning a value twice if it appears twice in array 2
        map[array2[i]] = 0;
    }
}

return result;
1
  • uses 2 loops. better than other solutions but you could bring it down to 1
    – jeremy
    Sep 15, 2012 at 1:03
2

With some ES6:

let sortedArray = [];
firstArr.map((first) => {
  sortedArray[defaultArray.findIndex(def => def === first)] = first;
});
sortedArray = sortedArray.filter(v => v);

This snippet also sorts the firstArr based on the order of the defaultArray

like:

let firstArr = ['apple', 'kiwi', 'banana'];
let defaultArray = ['kiwi', 'apple', 'pear'];
...
console.log(sortedArray);
// ['kiwi', 'apple'];
0

Iterate on array1 and find the indexof element present in array2.

var array1 = ["cat", "sum","fun", "run"];
var array2 = ["bat", "cat","sun", "hut", "gut"];
var str='';
for(var i=0;i<array1.length;i++){
        if(array2.indexOf(array1[i]) != -1){
           str+=array1[i]+' ';
       };
    }
console.log(str)
1
  • 1
    Only code is just not make sense. provide explanation for your answer what you giving to OP. Jun 2, 2018 at 17:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.