[英]Sort a JavaScript array of named objects by numeric named property
I've seen multiple similar questions to this, but I can't figure out how to apply the proposed solutions to a slightly different data structure.我已经看到了多个类似的问题,但我不知道如何将建议的解决方案应用于稍微不同的数据结构。
Here's an array of named objects that need to be sorted numerically by the property count
:这是一个命名对象数组,需要按属性
count
进行数字排序:
const myArray = [
{ABC:{label:'ABC', count:3}},
{EFG:{label:'EFG', count:10}},
{DEF:{label:'DEF', count:9}},
{FGH:{label:'FGH', count:1}}
]
And the resulting array after sorting should be like this:排序后的结果数组应该是这样的:
myArray = [
{FGH:{label:'FGH', count:1}},
{ABC:{label:'ABC', count:3}},
{DEF:{label:'DEF', count:9}},
{EFG:{label:'EFG', count:10}}
]
If the objects didn't have a name (ABC, DEF, etc) then the MDN web docs (along with multiple similar questions here) contain the solution for sorting such an array.如果对象没有名称(ABC、DEF 等),则MDN web 文档(以及此处的多个类似问题)包含对此类数组进行排序的解决方案。
That is, consider a slightly different array of unnamed objects:也就是说,考虑一个稍微不同的未命名对象数组:
const myArray1 = [
{label:'ABC', count:3},
{label:'EFG', count:10},
{label:'DEF', count:9},
{label:'FGH', count:1}
]
This one-liner works: myArray1.sort((a, b) => a.count - b.count)
to obtain:这个单线工作:
myArray1.sort((a, b) => a.count - b.count)
获得:
myArray1 = [
{label:'FGH', count:1},
{label:'ABC', count:3},
{label:'DEF', count:9},
{label:'EFG', count:10}
]
I know a more complex function expression is necessary to handle this, but I just don't know the language well enough (yet) to figure it out.我知道处理这个问题需要一个更复杂的 function 表达式,但我只是不太了解这种语言(还)无法弄清楚。
Just take the first (and only) object value first before comparing.在比较之前先取第一个(也是唯一的)object 值。
const myArray = [ {ABC:{label:'ABC', count:3}}, {EFG:{label:'EFG', count:10}}, {DEF:{label:'DEF', count:9}}, {FGH:{label:'FGH', count:1}} ] const getCount = obj => Object.values(obj)[0].count; myArray.sort((a, b) => getCount(a) - getCount(b)); console.log(myArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.