-1

We have a Mario Kart tournament at work and I wanted to try and log the results using basic JavaScript.

Here's the code: https://jsbin.com/hafati/44/edit?js,console

I've nearly got there, but I need help sorting the results.

Here's the console.log of the data:

[object Object] {
  1: [object Object] {
    id: 1,
    name: "Player 1",
    total: 20
  },
  2: [object Object] {
    id: 2,
    name: "Player 2",
    total: 60
  },
  3: [object Object] {
    id: 3,
    name: "Player 3",
    total: 80
  },
  4: [object Object] {
    id: 4,
    name: "Player 4",
    total: 400
  },
  5: [object Object] {
    id: 5,
    name: "Player 5",
    total: 150
  },
  6: [object Object] {
    id: 6,
    name: "Player 6",
    total: 50
  }
}

How would you sort these players, with the highest total first?

halfer
  • 19,824
  • 17
  • 99
  • 186
daveaspinall
  • 1,395
  • 1
  • 17
  • 28

3 Answers3

3

JavaScript array functions are polymorphic, so you can use them on "array like" objects just fine:

var obj = { 0 :  {total: 3}, 1 : {total: 1}, 2 : {total: 5}}; // your object
obj.length = 2; // need to set this manually.

var sorted = [].sort.call(obj, function(x,y){ return x.total - y.total; });

That said, it is always best to store sequential data in a sequential data structure like an array - so while this works it's not the best idea. I'm assuming you don't have a choice :)

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
1

Your need to store data in array of objects, this will be easier to iterate over array than objects and will also ensure the order of elements. Then you can use array sort function to sort the array elements.

Demo

var myArr = [{
  id: 1,
  name: "Player 1",
  total: 20
}, {
  id: 2,
  name: "Player 2",
  total: 60
}, {
  id: 3,
  name: "Player 3",
  total: 80
}, {
  id: 4,
  name: "Player 4",
  total: 400
}, {
  id: 5,
  name: "Player 5",
  total: 150
}, {
  id: 6,
  name: "Player 6",
  total: 50
}];


myArr.sort(function(a, b) {
  return a.total < b.total;
});
console.log(myArr);
Tushar
  • 85,780
  • 21
  • 159
  • 179
0

Put them in a array:

var score = [{
    id: 1,
    name: "Player 1",
    total: 20
  },{
    id: 2,
    name: "Player 2",
    total: 60
  },
  ...
}];

Then use Array.sort():

score.sort(function (a, b) {
   return a.total < b.total;
});
DrakaSAN
  • 7,673
  • 7
  • 52
  • 94