Sort array of objects

前端 未结 3 1593
情话喂你
情话喂你 2020-12-12 01:39

I have an array of object literals like this:

var myArr = [];

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

myArr[1] = {
   \'score\': 1,
   \'name\         


        
相关标签:
3条回答
  • 2020-12-12 02:10

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

    0 讨论(0)
  • 2020-12-12 02:10

    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

    0 讨论(0)
  • 2020-12-12 02:12

    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.
    0 讨论(0)
提交回复
热议问题