admin管理员组

文章数量:1302895

I have two javascript array and I need to pare 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 parison. What is the best and fastest way for doing that?

I have two javascript array and I need to pare 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 parison. What is the best and fastest way for doing that?

Share edited Mar 20, 2015 at 6:02 Randyka Yudhistira 3,6521 gold badge29 silver badges41 bronze badges asked Feb 25, 2015 at 6:55 hamedhamed 8,03316 gold badges65 silver badges119 bronze badges 6
  • 1 Your array can have same value repeated ? – Vaibhav Commented Feb 25, 2015 at 7:16
  • Yes, maybe they have some repeated value. – hamed Commented Feb 25, 2015 at 7:17
  • 1 I sincerely hope that the downvotes below didn't e from you, OP. – Passerby Commented Feb 25, 2015 at 7:19
  • No, I didn't down vote any answer. – hamed Commented Feb 25, 2015 at 7:22
  • Hmm, then normal index check will not work, we need to have the number of times a number is repeated. I have captured that in my solution, and time plexity is O(n), and Space plexity is also O(n) – Vaibhav Commented Feb 25, 2015 at 7:23
 |  Show 1 more ment

5 Answers 5

Reset to default 4

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

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 pare(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;

}

Try removing matching elements until both elements are empty:

var array1 = ["1", "2", "3", "4", "1", "5"];
var array2 = ["1", "5", "2", "3", "4", "1"];
var isSame = false;
if(array1.length != array2.length)
    isSame = false;
else
{
    for(var i = 0; i < array1.length; i ++)
    {
        var removed = false;
        for(var j = 0; j < array2.length; j ++)
        {
            if(array2[j] == array1[i])
            {
                //  remove from array2
                array1.splice(i, 1);
                //  remove from array1
                array2.splice(j, 1);
                //  go back 1 for i
                removed = true;
                i --;
                break;
            }
        }
        if(!removed)
            break;
}

    if(array1.length == 0 && array2.length == 0)
        isSame = true;
}

I don't suppose that is a fastest approach but it can be useful for a little arrays with primitives

function pareArrays(a, b) {
  var copyA = a.slice(),
      copyB = b.slice();

  if (a.length !== b.length) { return false; }
  return copyA.sort().toString() === copyB.sort().toString();

}

Return status from function after paring two array.

arr1 = [101,12,13,10,4];
arr2 = [101,4,12,13,10];


function pareTwoArray(arr1, arr2) {
  return arr1.length === arr2.length && 
  arr1.sort().every((val, index)=> val === arr2.sort()[index]);
}  
console.log(pareTwoArray(arr1, arr2))

本文标签: javascriptCompare elements of two arraysStack Overflow