'How does an array of numbers and its sorted version strictly equal to each other? [duplicate]
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
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
