javascript - 使用对象内部的对象对数组进行排序
问题描述
我有这个数组:
[
["name1", { count: 20 }],
["name2", { count: 10 }]
]
我将如何按计数值对该数组进行排序?
我尝试过使用排序功能,
const sort = Array.sort((a, b) => b.count - a.count);
但这并没有改变什么。
解决方案
您需要访问外部数组内的数组中的第二个条目。您的代码正在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;
}
推荐阅读
- kubernetes - kubernetes 找出 pod 中哪个容器崩溃
- android - 无论如何要获得recyclerview项目的拖放事件的持续时间吗?
- visual-studio-code - Visual Studio Code - 可以对“打开编辑器”面板进行排序吗?
- python - 带有字段增量的Odoo Cron?
- r - 如何估计多项式模型的 ROC 曲线
- node.js - proxyquire 不存根静态方法 - nodejs
- javascript - createMaterialTopTabNavigator 接受活动背景颜色
- c# - Xml 解析并绑定到 xamarin 表单上的列表视图
- angular - 是否可以在我的平台/主应用程序中包含 Angular 7 打包模块,该模块位于 Angular 6 中(也有其他具有 Angular 6 的应用程序)
- javascript - 如何在vue js中重新分配浏览器中的按钮?