1

I am trying to write an function to sort an array like this:

[
  {score:10, name:foo},
  {score:-10, name:bar},
  {score:0, name:newNAME}
]

into

[
  {rank:1, score:10, name:foo},
  {rank:2, score:0, name:newNAME},
  {rank:3, score:-10, name:bar}
]

But i found it is difficult to access the key(using score to sort and add a rank into each object).Is anyone can give me some hints to write such function?

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
Ken
  • 305
  • 1
  • 3
  • 10
  • If you don't have any issues using a library to do your sorting, I would suggest using lodash (https://lodash.com/) _orderBy method to order your array by score and then using es6 map function with index to add your ranks. – Phobos Dec 06 '19 at 07:00
  • First sort it in a desired way and iterate the array once again to set its rank – Rajaprabhu Aravindasamy Dec 06 '19 at 07:00

3 Answers3

5

You can use a custom sort and Array.prototype.map to add extra key rank to the array of objects.

let arr = [{
  score: 10,
  name: "foo"
}, {
  score: -10,
  name: "bar"
}, {
  score: 0,
  name: "newNAME"
}];

arr.sort((c1, c2) => {
  return c2.score - c1.score;
});

arr = arr.map((val, index) => {

  val.rank = index + 1;
  return val;
})

console.log(arr);
Akshay Bande
  • 2,491
  • 2
  • 12
  • 29
  • The `compareFunction` should return 0 when 2 values being compared are the same. Should be `arr.sort((c1, c2) => c2.score - c1.score)` – adiga Dec 06 '19 at 07:01
  • When both values are the same then it doesn't matter which comes first in sorted order. That's why I have not handled that case. Is there are any consequences of this? I would like to know. – Akshay Bande Dec 06 '19 at 07:03
  • The sorting will not keep the original relative order of the array and it will lead to inconsistent results in different browsers. – adiga Dec 06 '19 at 07:03
  • Okay thanks, I have updated my answer :) – Akshay Bande Dec 06 '19 at 07:04
1

You can use sorting and mapping in a one liner:

const sorted = [
      {score: 10, name: "foo"},
      {score: -10, name: "bar"},
      {score: 0, name: "newNAME"} ]
  .sort( (a, b) => a.score - b.score)
  .map( (v, i) => ({rank: i + 1, ...v}));

console.log(sorted);
.as-console-wrapper { top: 0; max-height: 100% !important; }
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1
const sorted = [
      {score: 10, name: "foo"},
      {score: -10, name: "bar"},
      {score: 0, name: "newNAME"} ]
  .sort( (a, b) => a.score - b.score)
  .map( (v, i) => ({rank: i + 1, ...v}));