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...
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.
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.
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.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With