6

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'
}

How would I sort the array so it ascends by the 'score' parameter such that it would change to:

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

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

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

Thanks in advance.

0

3 Answers 3

17

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.
Sign up to request clarification or add additional context in comments.

3 Comments

+1. And see this reference for why you use - rather than <.
@Tomalak Geret'kal: while you were typing your comment, I added a paragraph explaining that. Hopefully I was clear. It is a very good reference to see though!
Too much mucking about with Scheme and Haskell :(
5

You could have a look at the Array.sort documentation on MDN. Specifically at the documentation about providing a custom compareFunction

Comments

1

const myArray = [  
    {
   'score': 4,
   'name': 'foo'
},{
   'score': 1,
   'name': 'bar'
},{
   'score': 3,
   'name': 'foobar'
}
]

const myOrderedArray = _.sortBy(myArray, o => o.name);
console.log(myOrderedArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>

lodash sortBy

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.