2014-04-02 62 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但兩個數組不相等。