[javascript] How can I find matching values in two arrays?

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

This question is related to javascript arrays

The answer is


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'];

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)

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
    }
  }
}

use lodash

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

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

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!


You can use :

const intersection = array1.filter(element => array2.includes(element));

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;

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; 
});

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"]

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.

_x000D_
_x000D_
var array1 = ["cat", "sum","fun", "run"];_x000D_
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];_x000D_
_x000D_
found = array1.find( val => array2.includes(val) )_x000D_
console.log(found)
_x000D_
_x000D_
_x000D_


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


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"]