1

I have an array of objects with several key value pairs, and I need to sort them based on 'name':

[
    {
        "name" : "RAM",
        "value" : "12 GB"
    },
    {
        "name" : "Operating System",
        "value" : "Android"
    },
    {
        "name" : "Model",
        "value" : "Google Pixel XL"
    },
    {
        "name" : "Color",
        "value" : "Red"
    }
]

The result I want is as follows.

[   
    {
        "name" : "Color",
        "value" : "Red"
    },
    {
        "name" : "Model",
        "value" : "Google Pixel XL"
    },
    {
        "name" : "Operating System",
        "value" : "Android"
    },
    {
        "name" : "RAM",
        "value" : "12 GB"
    }
    
]

What's the most efficient way to do so?

Thanks in advance for your reply

  • Thank you to everyone who responded I got the result as follows ``` var data = [ {"name" : "RAM", "value": "12 GB"}, {"name":"Color", "value":"RED"}] function sortData( a, b ) { if (a.name < b.name){ return -1; } if (a.name > b.name){ return 1; } return 0; } data.sort(sortData) ``` – Abdulaxad Abdusamatov Jun 22 '20 at 07:33

2 Answers2

0

you could use: https://underscorejs.org/#sortBy, if you just import this specific method (rather than the whole library) it's tiny and perfect for this

their example:

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.sortBy(stooges, 'name');

=> [{name: 'curly', age: 60}, {name: 'larry', age: 50}, {name: 'moe', age: 40}];
Red Baron
  • 7,181
  • 10
  • 39
  • 86
  • why the downvote? OP asked for an efficient way, this is as efficient as it gets? – Red Baron Jun 22 '20 at 06:25
  • efficient is to use a built-in method. – Nina Scholz Jun 22 '20 at 06:55
  • @NinaScholz not necessarily. building your own method requires maintenance and thorough testing. of course, there are advantages and disadvantages to both. but I don't think it's worthy of a downvote. why would so many people use the library if it was more efficient to build your own. don't reinvent the wheel springs to mind – Red Baron Jun 22 '20 at 07:11
0

You can do something like this.

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}

xMayank
  • 1,875
  • 2
  • 5
  • 19