Sort an array of objects javascript

Hi All,

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

What makes you say it does those things?

When given two values, the job of that callback function is to say whether and which one is smaller than the other. What you describe is not part of that.

I came across a similar post on stackflow and the explanation below helped me understand more about the sort() method:

By default, the array sort() method sorts alphabetically ascending. If you want to sort in some other order, because your array contains numbers or objects then you can pass a function in to the sort() .

The function you pass in takes two parameters, often called a and b, and returns: a negative number if the first argument should be sorted before the second (a < b) 0 if the arguments are equal (a==b) a positive number if the first argument should be sorted after the second (a > b)

Now, here is the key bit :face_with_monocle: : the function you pass as a parameter to sort() will be called repeatedly by sort() as it processes the whole array. sort() doesn’t know or care about the datatype of the things in the array: each time it needs to know “Does item A come before item B?” it just calls your function. You don’t need to worry about what type of sort algorithm is used internally by sort() , indeed one browser might use a different algorithm to another, but that’s OK because you just have to provide a way for it to compare any two items from your array.

Your function could have an if / else if / else structure to decide what result to return, but for numbers simply returning (a-b) will achieve this for you because the result of the subtraction will be -ve, 0 or +ve and correctly put the numbers in ascending order.