简体   繁体   English

使用字符串值对对象数组进行排序 - javascript

[英]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 ).在上面的 Array 的 sort() 方法中,接受了一个回调 function,该回调将数组中包含的 2 个对象(我们称为 a 和 b )作为参数。

My query is how does the callback function know which value from the list array property to assign to the parameter.我的查询是回调 function 如何知道列表数组属性中的哪个值分配给参数。 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?例如 a.colour = white 和 b.colour = red 然后移动到下一个值,因为我们没有使用任何类型的循环来迭代列表?

Thanks Jag谢谢贾格

the Array.sort function does its own iterations... a and b parameters are any two objects in the Array as a whole. Array.sort function 进行自己的迭代... a 和 b 参数是整个数组中的任意两个对象。 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. 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酌情订购。 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 .该算法依靠回调告诉它a应该相对于b的位置。

Is a to the left of b ? ab的左边吗? to the right of b ?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排序算法可能将相同的原始值一次作为a传递,另一次作为b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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