Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Sort key value pair object based on value

I have an object like below. Trying to rearrange it in ascending order based on value. Similar to Javascript array sort method.

    var masterList = {     "1": "google",     "2": "yahoo",     "3": "msn",     "4": "stackoverflow",     "5": "github",     "6": "jsfiddle",     "7": "amazon",     "8": "ebay" } 

Please let me know the better solution...

like image 353
r1webs Avatar asked Jan 08 '13 05:01

r1webs


People also ask

How do you sort objects based on keys?

To sort the keys of an object:Use the Object. keys() method to get an array of the object's keys. Call the sort() method on the array. Call the reduce() method to get an object with sorted keys.

How do you sort an array object based on key-value?

const arr1 = ['d','a','b','c'] ; const arr2 = [{a:1},{c:3},{d:4},{b:2}]; We are required to write a JavaScript function that accepts these two arrays. The function should sort the second array according to the elements of the first array.

How do you sort objects by property?

In JavaScript, we use the sort() function to sort an array of objects. The sort() function is used to sort the elements of an array alphabetically and not numerically. To get the items in reverse order, we may use the reverse() method.


2 Answers

JavaScript objects have no order. Even though most browsers do iterate in the same order the properties were created, there's no guarantee, so sorting is not supported on objects.

See here for more info: Does JavaScript Guarantee Object Property Order?

You might also be interested in what John Resig has got to say on the matter.


If you need a sort-able list, you'll have to store it as an array of objects:

var masterList = [     { key: 1, val: "google" },     { key: 2, val: "yahoo" },     { key: 3, val: "msn" },     { key: 4, val: "stackoverflow" },     { key: 5, val: "github" },     { key: 6, val: "jsfiddle" },     { key: 7, val: "amazon" },     { key: 8, val: "ebay" } ]; 

Then, to sort them, just use the regular array's sort method:

masterList = masterList.sort(function (a, b) {     return a.val.localeCompare( b.val ); }); 

Here's the fiddle: http://jsfiddle.net/ASrUD/

like image 97
Joseph Silber Avatar answered Sep 30 '22 11:09

Joseph Silber


    var obj = {          "1": "google",          "2": "yahoo",          "3": "msn",          "4": "stackoverflow",          "5": "github",          "6": "jsfiddle",          "7": "amazon",          "8": "ebay"      };        var arr = [];        for (var key in obj) {          if (obj.hasOwnProperty(key)) {              arr.push(obj[key]);          }      }            alert(arr.sort());

This will sort your values in ascending order. let me give sometime will revert you with how to convert that to an object.

like image 45
satheeaseelan Avatar answered Sep 30 '22 10:09

satheeaseelan