Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare elements of two arrays

I have two javascript array and I need to compare them. For example, suppose I have these two arrays:

var array1 = ["1", "2", "3", "4"];
var array2 = ["4", "1", "3", "2"];

These arrays are equal in fact and I want to get true as a result of comparison. What is the best and fastest way for doing that?

like image 862
hamed Avatar asked Feb 25 '15 06:02

hamed


Video Answer


2 Answers

What you really have are two sets, not arrays, but unfortunately JavaScript does not provide any sort of "set" datatype. The easiest way to do this type of check is by using some sort of functional JavaScript library, such as lodash.

Using lodash's _.union function makes this trivially easy.

function setsEqual(a, b) {
  var u = _.union(a, b);
  return u.length === a.length && u.length === b.length;
}

If you want to do this without external libraries, you can do so using Array.prototype.every.

function setsEqual(a, b) {
  return a.length === b.length
      && a.every(function (v) { return b.indexOf(v) !== -1; });
}
like image 104
Alexis King Avatar answered Sep 24 '22 06:09

Alexis King


The best way and fastest way to do this is using object which keep tracks the value of and its count. Then we can see if it exist in second array. Try this

function compare(arr1, arr2){
    var obj={}, len = arr1.length, i=0, isSame=true, prop;
    if(arr1.length === arr2.length){
        for(;i<len;i++){
            if(obj[arr1[i]]){
                obj[arr1[i]] = obj[arr1[i]]+1;
            } else{
                obj[arr1[i]] =1;
            }
        }
        i=0, len = arr2.length;
        for(;i<len;i++){
            if(obj[arr2[i]]){
                obj[arr2[i]] = obj[arr2[i]]-1;
            } else{
                isSame = false;
                break;
            }
        }
        for (prop in obj){
            if(obj[prop] > 0){
                isSame = false;
                break;
            }
        }
    }else{
        isSame = false;
    }
    return isSame;

}
like image 29
Vaibhav Avatar answered Sep 22 '22 06:09

Vaibhav