JS - Why array.sort() doesn't return the same result for objects and numbers?

5

Sorting an array of objects (by a property of type number) doesn't return a sorted result like for an array of numbers.
Why so ?
How to make it sort like for numbers ?

Demo: Sorting an array of numbers

const sorted = [0,  5,  2, undefined,  3,  1,  4]
  .sort((a, b) => a - b);
  
console.log(sorted);

Demo: Sorting an array of objects

const notSorted = [
  {i:0},
  {i:5},
  {i:2},
  {i: undefined},
  {i:3},
  {i:1},
  {i:4},
]
  .sort((a, b) => a.i - b.i)
  .map(a => a.i);
  
console.log(notSorted);

I am currently on Chrome 90. Maybe some other browsers or engines don't have this issue. Tell me.

Share
Improve this question

Comments

Popular posts from this blog

flutter websocket connection issue

React-native : Unable to use react-native-fast-image

reinterpret_cast bug or UB? [duplicate]