2014-04-02 65 views
0

说我有两个数组如何比较的NodeJS两个数组

["a", "b", "c"] 

["c", "a", "b"] 

什么是比较这两个数组,看看他们是平等的最好方式(他们应该来对于上述方案作为平等的)

+0

可能重复的http://stackoverflow.com/questions/13523611/how-to-compare-two-arrays-in-node-js –

+0

显然是重复的;唯一缺失的链接是首先对两个比较数组进行预先排序。 – raina77ow

+0

@pronox该解决方案不起作用 > var arr1 = [“a”,“b”,“c”]; undefined > var arr2 = [“c”,“a”,“b”]; undefined > if(arr1.length == arr2.length ... && arr1.every(function(u,i){ ............ return u === arr2 [i]; ... ...}) ...){ ... console.log(true); ...} else { ... console.log(false); ...} 假 – bluesman

回答

4
function compareArrays(array1, array2) { 
    array1 = array1.slice(); 
    array2 = array2.slice(); 
    if (array1.length === array2.length) {  // Check if the lengths are same 
     array1.sort(); 
     array2.sort();       // Sort both the arrays 
     return array1.every(function(item, index) { 
      return item === array2[index];  // Check elements at every index 
     });          // are the same 
    } 
    return false; 
} 

console.assert(compareArrays(["a", "b", "c"], ["c", "a", "b"]) === true); 
+0

你正在改变阵列作为副作用 – Esailija

+0

@Esailija修复它:)请检查现在。 – thefourtheye

+0

当然,但为什么不''返回array1.length === array2.length && array1.every(item => array2.indexOf(item)> -1);'更简单,更快:P – Esailija

1

您可以_.difference

var diff = _(array1).difference(array2); 
if(diff.length > 0) { 
    // There is a difference 
} 

尝试这是行不通的,因为不同的回报ð iff来自第一个数组。 _.difference(['a'],['a','b'])为0但两个数组不相等。