-2
var a = [1,2,3]
var b = a.sort();

console.log('a',a,'b',b); // a [1,2,3] b [1,2,3]
console.log(a === b); // true

a = [1,3,2];
console.log(a.sort() === b) // false
console.log('a',a,'b',b); // a [1,2,3] b [1,2,3]
console.log(a === b) // false

My questions are - why? [I'm getting 2x false.] And additional one - it's possible to have original array untouched, maybe some parameter or other sorting function?

I mean:

var a = [1,3,2]; 
var b = a.SomeOtherSortFn();
console.log('a',a,'b',b); // a [1,3,2] b [1,2,3]

Edit: My goal wasn't to check if arrays are equal. Compare length, loop through values - no big deal. My question is - why arrays identical in the first place aren't identical in the second one.

I got my answer, thank you Arun Ghosh.

  • because sort() sorts the array – Kevin Kloet Oct 18 '16 at 09:58
  • 2
    Arrays aren't compared on their contents, especially not when using the `===` operator. Try `[1,2,3] == [1,2,3]`, it too is always `false`. You'll want to look up how comparison works, not worry about `sort`. – deceze Oct 18 '16 at 10:00
  • Possible duplicate of [How to determine equality for two JavaScript objects?](http://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) – Rajesh Oct 18 '16 at 10:01
  • sort() is a void type function. But is there a `return new array` type function? And my main question - why [1,2,3] is equal to [1[2,3] in the first place, but isn't in the second one? – Bogusz Michałowski Oct 18 '16 at 10:01
  • 1
    Because in the first code `a` and `b` are *exactly the same* array. Try it with `var a = [3,2,1]` and it'll still say that `a === b` is true. – JJJ Oct 18 '16 at 10:02
  • 1
    when you make a re-assignment like `a = [1,2,3]` you are in fact breaking the referral between `a` and `b` hence `a.sort() === b, // false`. – Redu Oct 18 '16 at 10:06

2 Answers2

4

When comparing two arrays the return value is true if they are referring to the same object. The values or the content of the arrays are not compared.

JJJ
  • 32,902
  • 20
  • 89
  • 102
Arun Ghosh
  • 7,634
  • 1
  • 26
  • 38
-1

Dont know very well which numbers are you using, but I guess you must use the optional parameter compareFunction: (you can read complete guide here)

var arr = [ 40, 1, 5, 200 ];
function comparar ( a, b ){ return a - b; }
arr.sort( comparar );  // [ 1, 5, 40, 200 ]

Because if you dont use it you will get this: (numbers ordered by unicode)

var arr = [ 40, 1, 5, 200 ];
arr.sort();  //[ 1, 200, 40, 5 ]