I’m learning about the sort method and wanted to know how it works.
Say we have an array of objects like this:
const list =
[ { color: ‘white’, size: ‘XXL’ }
, { color: ‘red’, size: ‘XL’ }
, { color: ‘black’, size: ‘M’ }
]
To sort this we can use the sort method as below:
list.sort((a, b) =>
(a.color > b.color)
? 1
: (a.color === b.color)
? ((a.size > b.size)
? 1
: -1)
: -1 )
In the above the sort() method of Array , takes a callback function, which takes as parameters 2 objects contained in the array (which we call a and b ).
My query is how does the callback function know which value from the list array property to assign to the parameter. for example a.colour = white and b.colour = red and then move to the next value as we are not using any kind of loop to iterate the list?
Thanks Jag