0

Say I have two arrays

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

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

What is the best way to compare these two arrays and see if they are equal (they should come as equal for the above scenario)

Sirko
  • 69,531
  • 19
  • 142
  • 174
bluesman
  • 2,184
  • 2
  • 24
  • 35
  • possible duplicat of http://stackoverflow.com/questions/13523611/how-to-compare-two-arrays-in-node-js – KKK Apr 02 '14 at 13:17
  • Clearly a duplicate; the only missing link is pre-sorting both compared arrays first. – raina77ow Apr 02 '14 at 13:19
  • @pronox That solution doesn't work > 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); ... } false – bluesman Apr 02 '14 at 13:22
  • then how is it marked accepted and up voted few times, let me check i – KKK Apr 02 '14 at 15:21
  • @bluesman its working – KKK Apr 02 '14 at 15:29
  • @pronox There was a missing step to sort the array as thefourtheye showed in his solution – bluesman Apr 03 '14 at 08:10

2 Answers2

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);
thefourtheye
  • 221,210
  • 51
  • 432
  • 478
0

You can try with _.difference

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

this will not work because different returns diff from first array. _.difference(['a'] ,['a','b']) is 0 but two array is not equal.

Aidin A
  • 33
  • 7
Fizer Khan
  • 80,049
  • 27
  • 138
  • 151