简体   繁体   English

使用对象内的对象对数组进行排序

[英]Sort array with Objects inside of Objects

I have this array:我有这个数组:

[
  ["name1", { count: 20 }],
  ["name2", { count: 10 }]
]

How would I go about sorting this array by the value of count?我将如何根据计数值对这个数组进行排序?

I have tried using the sort function,我曾尝试使用排序功能,

const sort = Array.sort((a, b) => b.count - a.count);

But this didn't change anything.但这并没有改变任何事情。

You need to access the second entry in the arrays inside the outer array.您需要访问外部数组内的数组中的第二个条目。 Your code is using count on the array entries, but they don't have a count property:您的代码在数组条目上使用count ,但它们没有count属性:

theArray.sort((a, b) => b[1].count - a[1].count);

Note also that you call sort on the actual array, not the Array constructor.另请注意,您对实际数组而不是Array构造函数调用sort It also sorts the array in-place, rather than returning a sorted array (it also returns the array you call it on, though).它还对数组进行就地排序,而不是返回已排序的数组(不过,它还返回您调用它的数组)。

Live Example:现场示例:

 const theArray = [ ["name1", { count: 20 }], ["name2", { count: 10 }], ["name3", { count: 15 }] ]; console.log("before:", theArray); theArray.sort((a, b) => b[1].count - a[1].count); console.log("after:", theArray);
 .as-console-wrapper { max-height: 100% !important; }

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

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