0

I want to sort an array of objects by a property from each object. For example I have this array:

var arr = [{name:"test",kills:4},{name:"test2",kills:1},{name:"test3",kills:7}]

I want to change the array so it will be sorted from the object with the max kills to the object with the minimum kills, the result that im looking for is:

[{name:"test3",kills:7},{name:"test",kills:4},{name:"test2",kills:1}]
NeNaD
  • 18,172
  • 8
  • 47
  • 89
Vrot
  • 1

2 Answers2

2

var arr = [{name:"test",kills:4},{name:"test2",kills:1},{name:"test3",kills:7}];
arr.sort((a,b) => b.kills - a.kills)
console.log(arr);
LaytonGB
  • 1,384
  • 1
  • 6
  • 20
Vivek Bani
  • 3,703
  • 1
  • 9
  • 18
1

var arr = [{name:"test",kills:4},{name:"test2",kills:1},{name:"test3",kills:7}];
arr.sort( (a, b) => a.kills < b.kills ? 1 : -1);
console.log(arr);
LaytonGB
  • 1,384
  • 1
  • 6
  • 20
Lrazerz
  • 164
  • 6
  • This is only correct if the "kills" property of two objects can never be the same. If it can, then this will produce inconsistent results. – Pointy Jun 05 '21 at 18:41
  • @Pointy Can you prove it? – Lrazerz Jun 05 '21 at 18:45
  • Like, create some snippet with an invalid result. – Lrazerz Jun 05 '21 at 18:47
  • Yes, easily. Two equal values should have the return value 0. If you don't do that, you're feeding bad data to the sort algorithm. Different browsers (with different sort code) may return different results. – Pointy Jun 05 '21 at 18:48