简体   繁体   中英

A more efficiently/performant way to add elements and sort an array

My function below returns an object containing the sorted playerPoints passed in via the "array of objects" parameter. Without modifying the passed in array, is there a more efficient/performant way to add elements and sort the array in ascending order?

Note: The array of objects could contain one or more objects. In terms of efficiency, I'm referring to completion time (speed). Also the function, ascendingSort is required and can't be replaced.

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

To simplify this function, you can use the map() method to map objects to playerPoints property. Also, you can change the regular function passed to the sort() method ( function(a, b) {return a - b;} ) to an 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) 

As for performance, I doubt there's a faster solution than that one you already have.

Can you just replace the function with

  function ascendingSort(players) {
      points.sort(function(a, b){return a["playerPoints"] - b["playerPoints"]});
      return {sortedPoints: players};
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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