0

I want to draw objects one by one sorted by y value, so objects that are "closer" won't be drawn behind objects that have lower y. I have array like this:

 List.list = [
 'idofobject' : {
  x: 20,
  y: 28
 },
 'otheridofobject' : {
  x: 20,
  y: 23
 },

];

How can i sort it by object y value? I tried to sort it like normal array of objects, but in this case i have id of object before properties, so it wasnt possible. How can i do this without deleting id of object?

Pointy
  • 405,095
  • 59
  • 585
  • 614
Stonoga
  • 1
  • 1
  • 1

3 Answers3

3

On one line

list.sort((obj1, obj2) => obj1.y - obj2.y);
Thai Tran
  • 9,815
  • 7
  • 43
  • 64
2

You can use the Array.Prototype.sort function like so :

List.list.sort(function(a, b) {
  return a.y - b.y;
});

This will sort using a custom function.

Take a look at the documentation if you need more informations.

Telokis
  • 3,399
  • 14
  • 36
-1

You can use if you want underscore

http://underscorejs.org/#sortBy

Dei Revoledo
  • 175
  • 1
  • 5
  • link only answers are of very little value. Provide relevant code based on link and only use link to support what is actually in the answer – charlietfl Feb 22 '17 at 00:47
  • Ok, I think the code in the link more clear imposible. But I appreciate your comment. – Dei Revoledo Feb 22 '17 at 00:51