Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 853
Daniel Avatar asked Sep 15 '12 00:09

Daniel


People also ask

How do you find elements that are duplicated in two arrays?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.

How do you check if two arrays contains same values?

To check if two arrays have the same elements:Use the every() to check if the arrays contain the same element at the same index. The every method only returns true if the condition is met for all array elements.


6 Answers

You can use :

const intersection = array1.filter(element => array2.includes(element));
like image 168
jota3 Avatar answered Oct 17 '22 04:10

jota3


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.

like image 44
jeremy Avatar answered Oct 17 '22 05:10

jeremy


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!

like image 33
Fred Read Avatar answered Oct 17 '22 05:10

Fred Read


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"]
like image 17
phant0m Avatar answered Oct 17 '22 04:10

phant0m


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"]
like image 12
David G Avatar answered Oct 17 '22 04:10

David G


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; 
});
like image 11
hardik beladiya Avatar answered Oct 17 '22 04:10

hardik beladiya