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)

6
  • possible duplicat of stackoverflow.com/questions/13523611/… Commented Apr 2, 2014 at 13:17
  • Clearly a duplicate; the only missing link is pre-sorting both compared arrays first. Commented Apr 2, 2014 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 Commented Apr 2, 2014 at 13:22
  • then how is it marked accepted and up voted few times, let me check i Commented Apr 2, 2014 at 15:21
  • @bluesman its working Commented Apr 2, 2014 at 15:29

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

12 Comments

You are changing the arrays as a side effect
@Esailija Fixed it :) Please check now.
Sure but why not return array1.length === array2.length && array1.every(item => array2.indexOf(item) > -1); much simpler and faster :P
@Esailija I test the solutions before I post them. That is ES6 and I couldn't test that :(
@Esailija Apart from that, technically that is O(N^2), I believe
|
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.