【发布时间】:2020-11-02 18:37:39
【问题描述】:
我正在尝试创建一个函数,它接收对值进行排序所需的对象的键(在本例中为“kills”)。我尝试使用Sort array of objects by string property value 中所述的dynamicSort,但我只是得到了返回的列表。关于我在这里做错了什么有什么想法吗?
const list = [
{
name: 'compass',
kills: 35,
assists: 312
},
{
name: 'another one',
kills: 52,
assists: 32
},
{
name: 'another anothe one',
kills: 12,
assists: 30
}
];
const sortByType = (property) => {
return function (a, b) {
let result;
if (a[property] < b[property]) {
result = -1;
}
if (a[property] > b[property]) {
result = 1;
}
else {
result = 0;
}
return result;
};
}
let newList = list.sort(sortByType('kills'));
console.log(newList);
已编辑:更新了代码的使用方式。
【问题讨论】:
-
展示你是如何使用它的。
-
请发帖minimal reproducible example。您可以使用Stack Snippet 使其可执行。
-
请注意,您的方法的全部内容可以简化为
return a[property] - b[property] -
@Taplar 这仅适用于数字数据,不适用于字符串。
-
当然可以,但考虑到他们目前的方法,它会是一样的。
标签: javascript sorting object