0

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

3
  • 1
    its the way the sort method works to take a function as a paramater. it is a higher order function. Commented Jun 25, 2020 at 0:10
  • 1
    sort only needs a way to compare two elements in the array and decide which one is larger, smaller, or equal. The two elements to compare are chosen by the sort algorithm and passed to the callback, and the swapping of elements is done by sort depending on the feedback it receives. The comparison callback only needs to let sort know the relation of each two elements it asks for. visualizing sort algos: math.hws.edu/eck/js/sorting/xSortLab.html stackoverflow.com/questions/3809288/… Commented Jun 25, 2020 at 1:20
  • Does this answer your question? Different sort algorithms visually performed Commented Jun 25, 2020 at 1:22

2 Answers 2

1

the Array.sort function does its own iterations... a and b parameters are any two objects in the Array as a whole. As you point out, JS doesn't REALLY know how to compare an object to another object...so you provide that detail with the compare function and the sort will use that compare function to compare pairs of objects in the Array and swap their order as appropriate. Just be aware that sorting changes the original array... it does not return a sorted copy.

0

The callback does not know.

It is used by the sorting algorithm that chooses the pair of values.

The sorting algorithm looks at pairs of values as it goes through the array.

The algorithm relies on the callback to tell it where a is supposed to be relative to b.

Is a to the left of b? to the right of b? or are their positions interchangeable because they're the same value

A sorting algorithm may pass the same original value once as a and another time as b

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.