简体   繁体   中英

Sort an array of objects with string value - javascript

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM