-3

Let's say we have an array of numbers in Javascript:

const arr = [1,3,2,6,5,3];

We sort it using the native sort method:

arr.sort(); // OR arr.sort((a, b) => a - b)

Now how do the unsorted and sorted array equal to one another?

console.log(arr === arr.sort()) // logs true 

I am aware the sort method does not create a new array, so they would both point to the same address on the memory.

However, their element order is different, and since arrays are list-like objects, with enumerable indices, the order of elements do matter unlike objects.

So, if all above is true, how are they strictly equal?

const arr = [1, 3, 2, 6, 5, 3];
arr.sort(); // OR arr.sort((a, b) => a - b)
console.log(arr === arr.sort()) // logs true
mplungjan
  • 169,008
  • 28
  • 173
  • 236
J Kim
  • 39
  • 7
  • 3
    `arr === arr.sort()` compares the reference of the arrays. `arr.sort` is an in-place sort. It doesn't create a new array. `arr` and `arr.sort()` reference the same object. – jabaa Mar 12 '22 at 12:40
  • Are you sure `console.log(arr === arr.sort())` is logging `true`? It logs `undefined` for me – Tushar Gupta Mar 12 '22 at 12:45
  • More proof: `const arr = [1,2,3,4]; const saveArr = arr; arr.length = 0; console.log(arr,saveArr,arr===saveArr);` – mplungjan Mar 12 '22 at 12:51
  • @Tushar Unlikely. See the snippet I made him – mplungjan Mar 12 '22 at 12:53
  • @Tushar you might be seeing the return value of the `.log()` method - it should show `true` above the `undefined`. – Nick Parsons Mar 12 '22 at 12:53
  • 2
    thanks @NickParsons and - mplungjan, I have used console.log on console which just returns .log() value. Stupid of me. – Tushar Gupta Mar 12 '22 at 12:58

1 Answers1

0

arr === arr.sort() compares the reference of the arrays. arr.sort is an in-place sort. It doesn't create a new array. arr and arr.sort() reference the same object.

They are strictly equal because both types (object) are same and both values (references) are same.

The comparison doesn't consider the values of the arrays.

[1,2,3] === [1,2,3] returns false, because the references are different.

jabaa
  • 5,844
  • 3
  • 9
  • 30