首页 > 解决方案 > 使用对象内部的对象对数组进行排序

问题描述

我有这个数组:

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

我将如何按计数值对该数组进行排序?

我尝试过使用排序功能,

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

但这并没有改变什么。

标签: javascriptarrayssorting

解决方案


您需要访问外部数组内的数组中的第二个条目。您的代码正在count数组条目上使用,但它们没有count属性:

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

另请注意,您调用sort的是实际数组,而不是Array构造函数。它还对数组进行就地排序,而不是返回排序后的数组(不过,它也会返回您调用它的数组)。

现场示例:

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;
}


推荐阅读