diffTwoArrays

function arr_diff (a1, a2) {
    var a = [], diff = [];
    for (var i = 0; i < a1.length; i++) {
        a[a1[i]] = true;
    }
    for (var i = 0; i < a2.length; i++) {
        if (a[a2[i]]) {
            delete a[a2[i]];
        } else {
            a[a2[i]] = true;
        }
    }
    for (var k in a) {
        diff.push(k);
    }
    return diff;
};
function diffArray(arr1, arr2) {
  var newArr = [];
  // Same, same; but different. 
  var diff1 = arr1.filter(function(x) { return arr2.indexOf(x) < 0; });
  var diff2 = arr2.filter(function(x) { return arr1.indexOf(x) < 0;});
  newArr = diff1.concat(diff2);
  return newArr;
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

发表评论

电子邮件地址不会被公开。 必填项已用*标注