1

Baffled as to why both console.logs output a sorted array. It's as if both console.log lines are being run at the end of the script. I was expecting the first console.log to output the unsorted array!? If I comment out the sort the array appears unsorted in the initial console output.

const notes=[
    {title: '2. My Next Trip', 
     body: 'I would like to go to Spain...'}, 
    {title: '3. Habits to Work On', 
     body: 'Exercise. Eating a bit better'}, 
    {title: '1. Office meditation', 
     body: 'Get a new seat'}
]
 
console.log(`Unsorted Array : `, notes)

notes.sort((a, b)=>{
    if(a.title < b.title) return -1
    else if(a.title > b.title) return 1
    else return 0
})
 
console.log(`Sorted Array : `, notes)

enter image description here

SMAKSS
  • 9,606
  • 3
  • 19
  • 34
user6746919
  • 67
  • 1
  • 9
  • It's logging the array by reference so after the sort is done, both logs will display the same, try `console.log(\`Unsorted Array : \`, notes.slice());`. – M0nst3R Jun 30 '20 at 17:13
  • It is not the issue of "by reference". The surprise is that the lines of code are not executed in sequence, at least those lines related to `console.log`. If things were run sequentially, the reference to the array at the time of the first `console.log` would have pointed to the unsorted array. – passerby51 Jul 19 '22 at 17:12

2 Answers2

1

Can't reproduce in Node.js.

Since you're doing this in the browser there's a chance that before the console.log object exploder can handle displaying your object you've already sorted it, as those can happen out of sequence.

Try making a copy first, then sorting:

sorted = [ ...notes ];

notes.sort(...)
tadman
  • 208,517
  • 23
  • 234
  • 262
0

It is because sort modified the array and the console reflects changes on the array when displaying it. You can see the difference if you use JSON.stringify on the array when logging it. In fact, stack snippets will also show the difference, as it does not dynamically apply changes on objects.

const notes=[
    {title: '2. My Next Trip', 
     body: 'I would like to go to Spain...'}, 
    {title: '3. Habits to Work On', 
     body: 'Exercise. Eating a bit better'}, 
    {title: '1. Office meditation', 
     body: 'Get a new seat'}
]
 
console.log(`Unsorted Array : `, notes)

notes.sort((a, b)=>{
    if(a.title < b.title) return -1
    else if(a.title > b.title) return 1
    else return 0
})
 
console.log(`Sorted Array : `, notes)

You could also make a shallow copy of the array to sort using slice.

const sorted = notes.slice().sort((a, b)=>{
    if(a.title < b.title) return -1
    else if(a.title > b.title) return 1
    else return 0
})
 
console.log(`Sorted Array : `, sorted);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80