我下面的函数返回一个对象,其中包含通过“对象数组”参数传入的排序后的 playerPoints
。在不修改传入数组的情况下,是否有更有效/性能更高的方法来添加元素并按升序对数组进行排序?
注意:对象数组可以包含一个或多个对象。在效率方面,我指的是完成时间(速度)。 ascendingSort 函数也是必需的,不能被替换。
var data = [{playerPoints: 10}, {playerPoints: 8}, {playerPoints: 2}, {playerPoints: 21},{playerPoints: 30}];
function ascendingSort(players) {
var points = [];
for(var i = 0; i < players.length; i++) {
points.push(players[i].playerPoints);
}
points.sort(function(a, b) {return a - b;});
return {sortedPoints: points};
}
var obj = ascendingSort(data);
console.log(obj);
最佳答案
为了简化这个函数,你可以使用the map()
method将对象映射到 playerPoints
属性。此外,您可以将传递给 sort()
方法的常规函数 (function(a, b) {return a - b;}
) 更改为 arrow function ((a, b) => a - b
).
const data = [{playerPoints: 10}, {playerPoints: 8}, {playerPoints: 2}, {playerPoints: 21},{playerPoints: 30}]
function ascendingSort(players) {
return {
sortedPoints: data.map(x => x.playerPoints).sort((a, b) => a - b)
}
}
const obj = ascendingSort(data)
console.log(obj)
至于性能,我怀疑是否有比您已有的解决方案更快的解决方案。
关于javascript - 添加元素和对数组排序的更有效/性能的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39268273/