Sort array of objects in javaScript

+4 votes
49 views
asked Dec 13, 2012 in java script by codeg (2,600 points)

i want to sort this array

 

I have an array of object literals like this:

var myArr = [];

myArr[0] = {
   'score': 4,
   'name': 'foo'
}

myArr[1] = {
   'score': 1,
   'name': 'bar'
}

myArr[2] = {
   'score': 3,
   'name': 'foobar'
}

1 Answer

0 votes
answered Dec 13, 2012 by sahana (2,250 points)

Try myArr.sort(function (a, b) {return a.score - b.score});

The way the array elements are sorted depends on what number the function passed in returns:

  • < 0 (negative number): a goes ahead of b
  • > 0 (positive number): b goes ahead of a
  • 0: In this cases the two numbers will be adjacent in the sorted list. However, the sort is not guaranteed to be stable: the order of a and b relative to each other may change.
...