991

If I have a JavaScript object such as:

var list = {
  "you": 100, 
  "me": 75, 
  "foo": 116, 
  "bar": 15
};

Is there a way to sort the properties based on value? So that I end up with

list = {
  "bar": 15, 
  "me": 75, 
  "you": 100, 
  "foo": 116
};
Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Steerpike
  • 17,163
  • 8
  • 39
  • 53
  • 5
    Not only "sorting," but more importantly sorting numbers. Numbers are immune to Javascripts Array.sort() method, meaning you'll not just have to find a method for sorting properties, but you'll have to write your own function to compare the numerical values. – Sampson Jul 01 '09 at 15:12
  • AFAIK, objects don't have any order like arrays do. – 0xc0de Oct 07 '16 at 05:42
  • 234
    **Before you read the answers:** The answer is ***No***. The ordering of object properties is non-standard in ECMAScript. You should never make assumptions about the order of elements in a JavaScript object. An Object is an unordered collection of properties. The answers below show you how to "use" sorted properties, using the help of arrays, but never actually alter the order of properties of objects themselves. **So, no, it's not possible.** Even if you build an object with presorted properties, it is not guaranteed that they will display in the same order in the future. Read on :). – Govind Rai Oct 29 '16 at 00:31
  • 10
    @GovindRai yet, in real world frontend applications we loop over object collections with IDs as the keys and the order is important if translated to HTML templates. You say they have no order, I say they have exactly the order that I see when console.logging them in the current browser. And that order can get reordered. As soon as you loop over them, they have an order. – ProblemsOfSumit Dec 19 '16 at 15:27
  • 9
    @GovindRai: **There is now** a means of accessing properties in a specified order in the spec. Is it a good idea? Almost certainly not. :-) But it's there, as of ES2015. – T.J. Crowder Dec 31 '16 at 16:22
  • 2
    @T.J.Crowder ah, you're absolutely right. Still, with all the caveats that come with this addition, I hope our fellow SO'ers will read the borderline before adopting of this new approach (as one always should). :D – Govind Rai Dec 31 '16 at 20:17
  • 20
    2019 visitors: check this barely upvoted `Object.entries`-based answer which is the cleanest and most readable state of the art since ES2017: https://stackoverflow.com/a/37607084/245966 – jakub.g May 03 '19 at 22:33
  • 1
    @jakub.g is right. The answer is as simple as `Object.entries(list).sort((a, b) => a[1] - b[1])`. It produces an ordered array with key/value pairs, but probably satisfies many requirements. – geotheory Jan 15 '20 at 13:58
  • Why on earth should you do this? – Black Mar 11 '20 at 11:10
  • 1
    Chrome (83) sorts properties by name when you use `console.log` so it may be confusing if you rely on this to check if your sorting worked. – Salah Jul 13 '20 at 09:47

45 Answers45

1093

Move them to an array, sort that array, and then use that array for your purposes. Here's a solution:

let maxSpeed = {
    car: 300, 
    bike: 60, 
    motorbike: 200, 
    airplane: 1000,
    helicopter: 400, 
    rocket: 8 * 60 * 60
};
let sortable = [];
for (var vehicle in maxSpeed) {
    sortable.push([vehicle, maxSpeed[vehicle]]);
}

sortable.sort(function(a, b) {
    return a[1] - b[1];
});

// [["bike", 60], ["motorbike", 200], ["car", 300],
// ["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]

Once you have the array, you could rebuild the object from the array in the order you like, thus achieving exactly what you set out to do. That would work in all the browsers I know of, but it would be dependent on an implementation quirk, and could break at any time. You should never make assumptions about the order of elements in a JavaScript object.

let objSorted = {}
sortable.forEach(function(item){
    objSorted[item[0]]=item[1]
})

In ES8, you can use Object.entries() to convert the object into an array:

const maxSpeed = {
    car: 300, 
    bike: 60, 
    motorbike: 200, 
    airplane: 1000,
    helicopter: 400, 
    rocket: 8 * 60 * 60
};

const sortable = Object.entries(maxSpeed)
    .sort(([,a],[,b]) => a-b)
    .reduce((r, [k, v]) => ({ ...r, [k]: v }), {});

console.log(sortable);

In ES10, you can use Object.fromEntries() to convert array to object. Then the code can be simplified to this:

const maxSpeed = {
    car: 300, 
    bike: 60, 
    motorbike: 200, 
    airplane: 1000,
    helicopter: 400, 
    rocket: 8 * 60 * 60
};

const sortable = Object.fromEntries(
    Object.entries(maxSpeed).sort(([,a],[,b]) => a-b)
);

console.log(sortable);
DisgruntledGoat
  • 70,219
  • 68
  • 205
  • 290
Nosredna
  • 83,000
  • 15
  • 95
  • 122
  • 26
    Can you please reformulate "you can rebuild" to "you can use array to maintain ordering of keys and pull values from object"? Not only it is non-standard, as you've yourself mentioned, this erroneous assumption is broken by more browsers than just Chrome today, so it's better not to encourage users to try it. – Oleg V. Volkov Aug 15 '12 at 15:42
  • 34
    Here is a more compact version of your code. Object.keys(maxSpeed).sort(function(a, b) {return -(maxSpeed[a] - maxSpeed[b])}); – TheBrain Sep 12 '12 at 11:07
  • 7
    @TheBrain: Just to add, `keys()` is only supported by IE9+ (and other modern browsers), if that is of concern. Also `keys()` excludes enumerable properties from the elements prototype chain (unlike for..in) - but that is usually more desirable. – MrWhite Nov 28 '12 at 09:07
  • Why not use insertion sort? Should be faster than converting back to an array were insertion sort is used any ways ( in Chrome for arrays with less than 10 elements ) and then back to an object. Blows my mind that this is not implemented on the prototype chain for objects. – employee-0 Nov 09 '13 at 01:49
  • 31
    `_.pairs` turns an object into [ [key1, value1], [key2, value2] ]. Then call sort on that. Then call `_.object` on it to turn it back. – dansch Feb 20 '14 at 14:45
  • Very Good Example! Thank you. If you want an DESC order -> replace the return statement with: return b[1] - a[1] – Combine Oct 30 '16 at 12:16
  • First of all the link doesn't exist anymore. Secondly, i am thinking that if the object is extremely huge, wouldn't it be too expensive to copy the entire thing into an array, perform the sort operation and back to an object? – Delali Mar 04 '17 at 21:52
  • If you sort `string keys`, then you can use: `return a[1] > b[1];`. – HoldOffHunger Jul 20 '18 at 20:21
  • 1
    Why do I have to search google to come back to this once a week – chimpsarehungry Oct 02 '18 at 15:40
  • 2
    My project requires object keys for merging cleanly, but also requires explicit sorting as the metadata drives UI. I followed a similar approach only I added a hasOwnProperty check to avoid crawling up the prototype chain. Here's a good article on iterating over object properties in JS https://hackernoon.com/5-techniques-to-iterate-over-javascript-object-entries-and-their-performance-6602dcb708a8 – Nathan Agersea Mar 01 '19 at 22:46
  • @OlegV.Volkov meaning this `var sortedAsObject = {}; sortable.forEach(function(item){sortedAsObject[item[0]]=item[1]})` – Adriano Sep 10 '19 at 17:53
  • For the above example, does `Object.fromEntries(Object.entries(maxSpeed).sort((a,b) => a[1]-b[1]));` work? – Winston Sep 16 '20 at 12:04
  • 2
    The ES8 example doesn't work, and have no idea how to fix. – Omiod Dec 21 '20 at 16:47
  • 4
    Am I crazy or does the ES10 solution not work? When I try it, Object.fromEntries creates an object sorted by key, undoing all the work of sorting. – Chase Denecke Apr 27 '21 at 00:00
  • 2
    Same here the ES10 solution does not work – BenjaminK Dec 13 '21 at 13:11
  • The ES10 solution works as expected for me: [REPL](https://ramdajs.com/repl/#?const%20maxSpeed%20%3D%20%7B%0A%20%20%20%20car%3A%20300%2C%20%0A%20%20%20%20bike%3A%2060%2C%20%0A%20%20%20%20motorbike%3A%20200%2C%20%0A%20%20%20%20airplane%3A%201000%2C%0A%20%20%20%20helicopter%3A%20400%2C%20%0A%20%20%20%20rocket%3A%208%20%2A%2060%20%2A%2060%0A%7D%3B%0A%0Aconst%20sortable%20%3D%20Object.fromEntries%28%0A%20%20%20%20Object.entries%28maxSpeed%29.sort%28%28%5B%2Ca%5D%2C%5B%2Cb%5D%29%20%3D%3E%20a%20-%20b%29%0A%29%3B%0A%0Aconsole.log%28sortable%29%3B) – Emman Mar 07 '22 at 13:24
  • how about if its a string? – Jenuel Ganawed Apr 08 '22 at 01:31
  • 1
    For people that are wondering what are these lambda parameters. `sort(([,a],[,b]) => a-b)` It means just declare a variable for the value of the entry. Commig from this syntax [key, value]. – Martin P. Aug 29 '22 at 18:43
  • Happy 1000th upvote! – Stephan Muller Sep 26 '22 at 15:07
509

We don't want to duplicate the entire data structure, or use an array where we need an associative array.

Here's another way to do the same thing as bonna:

var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
keysSorted = Object.keys(list).sort(function(a,b){return list[a]-list[b]})
console.log(keysSorted);     // bar,me,you,foo
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
Markus R
  • 5,572
  • 1
  • 14
  • 9
  • 33
    This seems to be sorting by key, not value, which is not what the question called for? – Michael Jan 07 '15 at 04:26
  • 1
    @Michael keysSorted contains the keys (you, me, etc.) on the latest versions of Safari, Chrome, and Firefox at the time of this writing, and they are sorted by value. – mota May 11 '15 at 09:36
  • 42
    It's sorted by value, and displays keys -- but we lose the value count when it prints out, as it prints only keys. – Hanna Jul 22 '15 at 21:16
  • 8
    Object property order is not guaranteed in JavaScript, so sorting should be done into an array, not an object (which is what you are referring to as an 'associative array'). – Christopher Meyers Nov 06 '15 at 20:59
  • @ChristopherMeyers makes a very valid point! I used this but got me unexpected results. – Evers Mar 02 '16 at 09:10
  • 5
    @ChristopherMeyers The sorting *is* done in an array. It is obtained from Object.keys(), then sorted by comparing the values in the original object. – Markus R Jul 19 '16 at 07:59
  • 1
    @Johannes If the intention is to print the values, you have to iterate over the sorted keys and print the values from the original data structure - which we have not lost. – Markus R Jul 19 '16 at 08:10
  • 3
    @MarkusR So it is. So it is. Not sure what my problem was. Good answer! – Christopher Meyers Jul 19 '16 at 08:13
  • @Michael It is sorting by value. We tell sort() to compare values in this part: function(a,b){return list[a] -list[b]} – Markus R Jul 19 '16 at 08:14
  • 9
    Don't forget. `keysSorted` is an array! Not an object! – Green Feb 06 '17 at 15:14
  • 31
    If you add `.map(key => list[key]);` to the end of the sort, it will return the whole object instead of just the key – James Moran Jan 10 '18 at 15:00
  • 5
    @JamesMoran adding that would just return the value for that key, not the entire object. – DollarAkshay Apr 21 '21 at 01:24
  • 2
    Agree with @DollarAkshay, instead one needs to use `.map((key) => ({ [key]: list[key] }))` to return array of objects. – Edgar Manukyan May 18 '22 at 01:49
  • `reduce` can be used to return the entire sorted object: `Object.keys(list).sort((a,b) => list[a]-list[b]).reduce((r, k) => ({...r, [k]: list[k]}), {});` – Christopher Peisert Oct 14 '22 at 17:37
  • Use `.reverse()` at the end of the `sort` if you then want the first item in the array to be the largest – ckhatton Aug 08 '23 at 09:18
253

Your objects can have any amount of properties and you can choose to sort by whatever object property you want, number or string, if you put the objects in an array. Consider this array:

var arrayOfObjects = [   
    {
        name: 'Diana',
        born: 1373925600000, // Mon, Jul 15 2013
        num: 4,
        sex: 'female'
    },
    {

        name: 'Beyonce',
        born: 1366832953000, // Wed, Apr 24 2013
        num: 2,
        sex: 'female'
    },
    {            
        name: 'Albert',
        born: 1370288700000, // Mon, Jun 3 2013
        num: 3,
        sex: 'male'
    },    
    {
        name: 'Doris',
        born: 1354412087000, // Sat, Dec 1 2012
        num: 1,
        sex: 'female'
    }
];

sort by date born, oldest first

// use slice() to copy the array and not just make a reference
var byDate = arrayOfObjects.slice(0);
byDate.sort(function(a,b) {
    return a.born - b.born;
});
console.log('by date:');
console.log(byDate);

sort by name

var byName = arrayOfObjects.slice(0);
byName.sort(function(a,b) {
    var x = a.name.toLowerCase();
    var y = b.name.toLowerCase();
    return x < y ? -1 : x > y ? 1 : 0;
});

console.log('by name:');
console.log(byName);

http://jsfiddle.net/xsM5s/16/

inorganik
  • 24,255
  • 17
  • 90
  • 114
143

ECMAScript 2017 introduces Object.values / Object.entries. As the name suggests, the former aggregates all the values of an object into an array, and the latter does the whole object into an array of [key, value] arrays; Python's equivalent of dict.values() and dict.items().

The features make it pretty easier to sort any hash into an ordered object. As of now, only a small portion of JavaScript platforms support them, but you can try it on Firefox 47+.

EDIT: Now supported by all modern browsers!

let obj = {"you": 100, "me": 75, "foo": 116, "bar": 15};

let entries = Object.entries(obj);
// [["you",100],["me",75],["foo",116],["bar",15]]

let sorted = entries.sort((a, b) => a[1] - b[1]);
// [["bar",15],["me",75],["you",100],["foo",116]]
kiding
  • 1,735
  • 1
  • 11
  • 7
  • how does this possibly answers the question's title `Sorting JavaScript Object by property value` ? you misunderstood the question I think, since you are to change the original Object and not create a new Array from it. – vsync Jun 14 '17 at 15:15
  • 6
    @vsync This answer gives the same result as the accepted answer, but with less code and no temporary variable. – Darren Cook Apr 03 '18 at 18:18
  • 13
    FWIW, this answer is clean af and is the only one that helped me. – NetOperator Wibby Apr 20 '18 at 23:04
  • only in ff, not ie, nor chrome anymore they sort the objects automaticly. wtf – f b Jun 27 '19 at 20:06
  • 1
    Just note that this will not preserve keys. – Vael Victus Dec 08 '19 at 18:31
  • 5
    For even further simplification, combine the process into one line: ```let sorted = Object.entries(obj).sort((a, b) => a[1] - b[1]); ``` – Avid Oct 11 '21 at 17:49
73

For completeness sake, this function returns sorted array of object properties:

function sortObject(obj) {
    var arr = [];
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            arr.push({
                'key': prop,
                'value': obj[prop]
            });
        }
    }
    arr.sort(function(a, b) { return a.value - b.value; });
    //arr.sort(function(a, b) { return a.value.toLowerCase().localeCompare(b.value.toLowerCase()); }); //use this to sort as strings
    return arr; // returns array
}

var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
var arr = sortObject(list);
console.log(arr); // [{key:"bar", value:15}, {key:"me", value:75}, {key:"you", value:100}, {key:"foo", value:116}]

JSFiddle with the code above is here. This solution is based on this article.

Updated fiddle for sorting strings is here. You can remove both additional .toLowerCase() conversions from it for case sensitive string comparation.

Ben Holness
  • 2,457
  • 3
  • 28
  • 49
Stano
  • 8,749
  • 6
  • 30
  • 44
63

An "arrowed" version of @marcusR 's answer for reference

var myObj = { you: 100, me: 75, foo: 116, bar: 15 };
keysSorted = Object.keys(myObj).sort((a, b) => myObj[a] - myObj[b]);
alert(keysSorted); // bar,me,you,foo

UPDATE: April 2017 This returns a sorted myObj object defined above.

const myObj = { you: 100, me: 75, foo: 116, bar: 15 };
const result =
  Object.keys(myObj)
    .sort((a, b) => myObj[a] - myObj[b])
    .reduce(
      (_sortedObj, key) => ({
        ..._sortedObj,
        [key]: myObj[key]
      }),
      {}
    );
document.write(JSON.stringify(result));

UPDATE: March 2021 - Object.entries with sort function (updated as per comments)

const myObj = { you: 100, me: 75, foo: 116, bar: 15 };
const result = Object
 .entries(myObj)
 .sort((a, b) => a[1] - b[1])
 .reduce((_sortedObj, [k,v]) => ({
   ..._sortedObj, 
   [k]: v
 }), {})
document.write(JSON.stringify(result));
Jason J. Nathan
  • 7,422
  • 2
  • 26
  • 37
  • 2
    does not work for `var myObj = {"1": {"Value": 40}, "2": {"Value": 10}, "3": {"Value": 30}, "4": {"Value": 20}};` – Rohanil Jan 05 '18 at 10:03
  • 9
    The OP's question, along with this answer does not contain nested objects @Rohanil Maybe you'd want to ask another question instead of down-voting. Your nested object with various types obviously needs more than this solution provides – Jason J. Nathan Jan 06 '18 at 12:21
  • Just a note: your updates won't work actually. At least not everywhere and not because of `entries`. According to the standard, an object _is an unordered collection of properties_. Well, that means if you are trying to construct the new object after sorting it by property value or anything else, the property key ordering becomes again undefined. Chrome, for example, is by default ordering the property keys, thus every attempt to order them differently is useless. Your only chance is to get an "index" based on your ordering preferences and traverse the original object accordingly. – ZorgoZ Oct 25 '18 at 10:49
  • Yes @ZorgoZ, you are right and many people have mentioned it on this post. Most of the time, we use this function as a transformation before converting to another type (like JSON) or before another reduce function. If the objective is to mutate the object thereafter, then there might be unexpected results. I have had success with this function across engines. – Jason J. Nathan Oct 28 '18 at 23:07
  • Note: you don't want to use `sort()` on `Object.entries()` – png Feb 04 '19 at 22:15
  • `Object.assign()` would be so much more performant than spreading `_sortedObj` in the reduce – DiegoRBaquero Mar 08 '19 at 20:03
  • Not sure that is accurate DiegoRBaquero. – Jason J. Nathan Mar 26 '19 at 00:01
  • Tried with the UPDATE: October 2018 version, but the result is incorrect. I am receiving ``// {bar: 15, foo: 116, me: 75, you: 100}`` but the expected result is ``// {bar: 15, me: 75, you: 100, foo: 116}`` Order is fundamentally based on value. (15,75,100,116). Not in the key. (b, f, m, y) – Jasp402 Jul 09 '20 at 16:15
  • The July 2020 update seems broken, at least in Chrome. It just outputs the same order as input `{"bar": 15, "foo": 116, "me": 75, "you": 100}` – SubJunk Jul 29 '20 at 23:18
  • Confirmed: your 2018 and 2020 solutions don't sort correctly, as you can see in your own Ramda REPL links. This has ***nothing*** to do with Chrome. – Henke Mar 17 '21 at 15:44
38

JavaScript objects are unordered by definition (see the ECMAScript Language Specification, section 8.6). The language specification doesn't even guarantee that, if you iterate over the properties of an object twice in succession, they'll come out in the same order the second time.

If you need things to be ordered, use an array and the Array.prototype.sort method.

NickFitz
  • 34,537
  • 8
  • 43
  • 40
  • 4
    Note that's there's been quite a bit of arguing about this. Most implementations keep the list in the order in which elements were added. IIRC, Chrome doesn't. There was argument about whether Chrome should fall in line with the other implementations. My belief is that a JavaScript object is a hash and no order should be assumed. I believe Python went through the same argument and a new ordered hash-like list was recently introduced. For most browsers, you CAN do what you want by recreating your object, adding elements by sorted value. But you shouldn't. – Nosredna Jul 01 '09 at 15:37
  • Edit. Chrome usually keeps order, but doesn't always. And here's the relevant Chromium bug: http://code.google.com/p/chromium/issues/detail?id=883 – Nosredna Jul 01 '09 at 15:43
  • 8
    That bug report is unjustified, and those who relied on the undocumented behaviour are the ones with the bugs. Read ECMASCript section 8.6; it clearly states that "An Object is an unordered collection of properties". Anybody who found that it didn't seem that way in a few implementations, and then started to depend on that implementation-specific behaviour,made a big mistake, and they shouldn't be trying to shift the blame away from themselves. If I was on the Chrome team I'd mark that bug report as "Invalid, WontFix". – NickFitz Jul 01 '09 at 15:58
  • But why would Chrome want to break on pages that work on other browsers? I agree with your sentiment, though. Should not rely on order. – Nosredna Jul 01 '09 at 19:27
  • 8
    EcmaScript 5 actually defines the order of enumeration to be the order of insertion -- the absence of definition is considered a spec bug in ES3. It's worth noting that the EcmaScript spec defines behaviour that no one would consider sane -- for example spec behaviour is that syntax errors are in many cases thrown at runtime, incorrect use of continue, break, ++, --, const, etc according to the spec any engine that throws an exception before reaching that code is *wrong* – olliej Jul 01 '09 at 21:24
  • 5
    @olliej - I don't think this is correct. The spec says: "The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified". This is on page 92 of the PDF of the final draft. – whitneyland Feb 20 '12 at 17:06
  • @whitneyland - You're quite right that ES5 did not define an order to object properties. ES2015 did several years later (it's *not* just insertion order as olliej's comment suggests above), but exempted some operations. Those were un-exempted by later specs. Here in 2020, there is an order and it applies to the operations you'd expect (`for-in`, `Object.keys`, etc.), but it's *still* not a good idea to rely on it. :-) – T.J. Crowder Oct 20 '20 at 15:08
36

OK, as you may know, javascript has sort() function, to sort arrays, but nothing for object...

So in that case, we need to somehow get array of the keys and sort them, thats the reason the apis gives you objects in an array most of the time, because Array has more native functions to play with them than object literal, anyway, the quick solotion is using Object.key which return an array of the object keys, I create the ES6 function below which does the job for you, it uses native sort() and reduce() functions in javascript:

function sortObject(obj) {
  return Object.keys(obj)
    .sort().reduce((a, v) => {
    a[v] = obj[v];
    return a; }, {});
}

And now you can use it like this:

let myObject = {a: 1, c: 3, e: 5, b: 2, d: 4};
let sortedMyObject = sortObject(myObject);

Check the sortedMyObject and you can see the result sorted by keys like this:

{a: 1, b: 2, c: 3, d: 4, e: 5}

Also this way, the main object won't be touched and we actually getting a new object.

I also create the image below, to make the function steps more clear, in case you need to change it a bit to work it your way:

Sorting a javascript object by property value

Alireza
  • 100,211
  • 27
  • 269
  • 172
12

Update with ES6: If your concern is having a sorted object to iterate through (which is why i'd imagine you want your object properties sorted), you can use the Map object.

You can insert your (key, value) pairs in sorted order and then doing a for..of loop will guarantee having them loop in the order you inserted them

var myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one");
for (var [key, value] of myMap) {
  console.log(key + " = " + value);
}
// 0 = zero 
// 1 = one
julianljk
  • 1,297
  • 10
  • 12
  • Also in ES6 (ES2015): Object properties *do* have order (or there is a means of accessing them in a defined order, depending on your point of view). If the property names are strings and don't look like array indexes, the order is the order they were added to the object. This order is **not** specified to be respected by `for-in` or `Object.keys`, but it **is** defined to be respected by `Object.getOwnPropertyNames` and the other new methods for accessing property name arrays. So that's another option. – T.J. Crowder Dec 31 '16 at 16:26
  • But where is `sort' operation? They are not sorted at all – Green Feb 06 '17 at 15:21
  • @Green I think what I wanted to highlight here is that, with `Map` you actually have a data structure that can store in sorted order (sort your data, loop through it and store it in the map) where as you aren't guaranteed that with objects. – julianljk Feb 07 '17 at 16:08
10
var list = {
    "you": 100, 
    "me": 75, 
    "foo": 116, 
    "bar": 15
};

function sortAssocObject(list) {
    var sortable = [];
    for (var key in list) {
        sortable.push([key, list[key]]);
    }
    // [["you",100],["me",75],["foo",116],["bar",15]]

    sortable.sort(function(a, b) {
        return (a[1] < b[1] ? -1 : (a[1] > b[1] ? 1 : 0));
    });
    // [["bar",15],["me",75],["you",100],["foo",116]]

    var orderedList = {};
    for (var idx in sortable) {
        orderedList[sortable[idx][0]] = sortable[idx][1];
    }

    return orderedList;
}

sortAssocObject(list);

// {bar: 15, me: 75, you: 100, foo: 116}
Vasil Nikolov
  • 1,112
  • 10
  • 17
9

Sort values without multiple for-loops (to sort by the keys change index in the sort callback to "0")

const list = {
    "you": 100, 
    "me": 75, 
    "foo": 116, 
    "bar": 15
  };

let sorted = Object.fromEntries(
                Object.entries(list).sort( (a,b) => a[1] - b[1] )    
             ) 
console.log('Sorted object: ', sorted) 
daniil4udo
  • 101
  • 2
  • 4
9

Very short and simple!

var sortedList = {};
Object.keys(list).sort((a,b) => list[a]-list[b]).forEach((key) => {
    sortedList[key] = list[key]; });
orad
  • 15,272
  • 23
  • 77
  • 113
Maryam Koulaei
  • 750
  • 2
  • 9
  • 17
8

Underscore.js or Lodash.js for advanced array or object sorts

var data = {
  "models": {

    "LTI": [
      "TX"
    ],
    "Carado": [
      "A",
      "T",
      "A(пасс)",
      "A(груз)",
      "T(пасс)",
      "T(груз)",
      "A",
      "T"
    ],
    "SPARK": [
      "SP110C 2",
      "sp150r 18"
    ],
    "Autobianchi": [
      "A112"
    ]
  }
};

var arr = [],
  obj = {};
for (var i in data.models) {
  arr.push([i, _.sortBy(data.models[i], function(el) {
    return el;
  })]);
}
arr = _.sortBy(arr, function(el) {
  return el[0];
});
_.map(arr, function(el) {
  return obj[el[0]] = el[1];
});
console.log(obj);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js" integrity="sha256-qXBd/EfAdjOA2FGrGAG+b3YBn2tn5A6bhz+LSgYD96k=" crossorigin="anonymous"></script>
tagurit
  • 494
  • 5
  • 13
Roman Yudin
  • 924
  • 10
  • 8
5

I am following the solution given by slebetman (go read it for all the details), but adjusted, since your object is non-nested.

// First create the array of keys/values so that we can sort it:
var sort_array = [];
for (var key in list) {
    sort_array.push({key:key,value:list[key]});
}

// Now sort it:
sort_array.sort(function(x,y){return x.value - y.value});

// Now process that object with it:
for (var i=0;i<sort_array.length;i++) {
    var item = list[sort_array[i].key];

    // now do stuff with each item
}
Community
  • 1
  • 1
bonna
  • 1,575
  • 2
  • 17
  • 31
4
let toSort = {a:2323, b: 14, c: 799} 
let sorted = Object.entries(toSort ).sort((a,b)=> a[1]-b[1]) 

Output:

[ [ "b", 14 ], [ "c", 799 ], [ "a", 2323 ] ]
4b0
  • 21,981
  • 30
  • 95
  • 142
4

There are many ways to do this, but since I didn't see any using reduce() I put it here. Maybe it seems utils to someone.

var list = {
    "you": 100,
    "me": 75,
    "foo": 116,
    "bar": 15
};

let result = Object.keys(list).sort((a,b)=>list[a]>list[b]?1:-1).reduce((a,b)=> {a[b]=list[b]; return a},{});

console.log(result);
Jasp402
  • 402
  • 3
  • 12
4

Thanks to @orad for providing the answer in TypeScript. Now, We can use the below codesnippet in JavaScript.

function sort(obj,valSelector) {
  const sortedEntries = Object.entries(obj)
    .sort((a, b) =>
      valSelector(a[1]) > valSelector(b[1]) ? 1 :
      valSelector(a[1]) < valSelector(b[1]) ? -1 : 0);
  return new Map(sortedEntries);
}

const Countries = { "AD": { "name": "Andorra", }, "AE": { "name": "United Arab Emirates", }, "IN": { "name": "India", }} 

// Sort the object inside object. 
var sortedMap = sort(Countries, val => val.name); 
// Convert to object. 
var sortedObj = {}; 
sortedMap.forEach((v,k) => { sortedObj[k] = v }); console.log(sortedObj); 

//Output: {"AD": {"name": "Andorra"},"IN": {"name": "India"},"AE": {"name": "United Arab Emirates"}}
VenkateshMogili
  • 591
  • 4
  • 5
4

Sorting object property by values

const obj = { you: 100, me: 75, foo: 116, bar: 15 };
const keysSorted = Object.keys(obj).sort((a, b) => obj[a] - obj[b]);
const result = {};
keysSorted.forEach(key => { result[key] = obj[key]; });
document.write('Result: ' + JSON.stringify(result));

The desired output:

{"bar":15,"me":75,"you":100,"foo":116}

References:

Henke
  • 4,445
  • 3
  • 31
  • 44
3

This could be a simple way to handle it as a real ordered object. Not sure how slow it is. also might be better with a while loop.

Object.sortByKeys = function(myObj){
  var keys = Object.keys(myObj)
  keys.sort()
  var sortedObject = Object()
  for(i in keys){
    key = keys[i]
    sortedObject[key]=myObj[key]
   }

  return sortedObject

}

And then I found this invert function from: http://nelsonwells.net/2011/10/swap-object-key-and-values-in-javascript/

Object.invert = function (obj) {

  var new_obj = {};

  for (var prop in obj) {
    if(obj.hasOwnProperty(prop)) {
      new_obj[obj[prop]] = prop;
    }
  }

  return new_obj;
};

So

var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
var invertedList = Object.invert(list)
var invertedOrderedList = Object.sortByKeys(invertedList)
var orderedList = Object.invert(invertedOrderedList)
Carson Wright
  • 323
  • 3
  • 12
3

Just in case, someone is looking for keeping the object (with keys and values), using the code reference by @Markus R and @James Moran comment, just use:

var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
var newO = {};
Object.keys(list).sort(function(a,b){return list[a]-list[b]})
                 .map(key => newO[key] = list[key]);
console.log(newO);  // {bar: 15, me: 75, you: 100, foo: 116}
esneyderp
  • 111
  • 1
  • 12
3
<pre>
function sortObjectByVal(obj){  
var keysSorted = Object.keys(obj).sort(function(a,b){return obj[b]-obj[a]});
var newObj = {};
for(var x of keysSorted){
    newObj[x] = obj[x];
}
return newObj;

}
var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
console.log(sortObjectByVal(list));
</pre>
  • 2
    Welcome to stackoverflow. In addition to the answer you've provided, please consider providing a brief explanation of why and how this fixes the issue. – jtate May 13 '20 at 19:34
2

Object sorted by value (DESC)

function sortObject(list) {
  var sortable = [];
  for (var key in list) {
    sortable.push([key, list[key]]);
  }

  sortable.sort(function(a, b) {
    return (a[1] > b[1] ? -1 : (a[1] < b[1] ? 1 : 0));
  });

  var orderedList = {};
  for (var i = 0; i < sortable.length; i++) {
    orderedList[sortable[i][0]] = sortable[i][1];
  }

  return orderedList;
}
victorhazbun
  • 786
  • 8
  • 16
2
    var list = {
    "you": 100,
    "me": 75,
    "foo": 116,
    "bar": 15
};
var tmpList = {};
while (Object.keys(list).length) {
    var key = Object.keys(list).reduce((a, b) => list[a] > list[b] ? a : b);
    tmpList[key] = list[key];
    delete list[key];
}
list = tmpList;
console.log(list); // { foo: 116, you: 100, me: 75, bar: 15 }
2
a = { b: 1, p: 8, c: 2, g: 1 }
Object.keys(a)
  .sort((c,b) => {
    return a[b]-a[c]
  })
  .reduce((acc, cur) => {
    let o = {}
    o[cur] = a[cur]
    acc.push(o)
    return acc
   } , [])

output = [ { p: 8 }, { c: 2 }, { b: 1 }, { g: 1 } ]

Michael Curry
  • 991
  • 8
  • 20
2

TypeScript

The following function sorts object by value or a property of the value. If you don't use TypeScript you can remove the type information to convert it to JavaScript.

/**
 * Represents an associative array of a same type.
 */
interface Dictionary<T> {
  [key: string]: T;
}

/**
 * Sorts an object (dictionary) by value or property of value and returns
 * the sorted result as a Map object to preserve the sort order.
 */
function sort<TValue>(
  obj: Dictionary<TValue>,
  valSelector: (val: TValue) => number | string,
) {
  const sortedEntries = Object.entries(obj)
    .sort((a, b) =>
      valSelector(a[1]) > valSelector(b[1]) ? 1 :
      valSelector(a[1]) < valSelector(b[1]) ? -1 : 0);
  return new Map(sortedEntries);
}

Usage

var list = {
  "one": { height: 100, weight: 15 },
  "two": { height: 75, weight: 12 },
  "three": { height: 116, weight: 9 },
  "four": { height: 15, weight: 10 },
};

var sortedMap = sort(list, val => val.height);

The order of keys in a JavaScript object are not guaranteed, so I'm sorting and returning the result as a Map object which preserves the sort order.

If you want to convert it back to Object, you can do this:

var sortedObj = {} as any;
sortedMap.forEach((v,k) => { sortedObj[k] = v });
orad
  • 15,272
  • 23
  • 77
  • 113
  • can I have this in javascript, please. – Sudipta Dhara Aug 04 '20 at 12:08
  • Thank you very much, this solution worked for me. I have used the same thing in Javascript without Dictionary interface. const Countries = { "AD": { "name": "Andorra", }, "AE": { "name": "United Arab Emirates", }, "IN": { "name": "India", }, } // Sort the object inside object. var sortedMap = sort(Countries, val => val.name); // Convert to object. var sortedObj = {}; sortedMap.forEach((v,k) => { sortedObj[k] = v }); console.log(sortedObj); Output: {"AD": {"name": "Andorra"},"IN": {"name": "India"},"AE": {"name": "United Arab Emirates"}} – VenkateshMogili Oct 17 '20 at 10:09
2
const arrayOfObjects = [
{name: 'test'},
{name: 'test2'}
]

const order = ['test2', 'test']

const setOrder = (arrayOfObjects, order) =>
    arrayOfObjects.sort((a, b) => {
        if (order.findIndex((i) => i === a.name) < order.findIndex((i) => i === b.name)) {
            return -1;
        }

        if (order.findIndex((i) => i === a.name) > order.findIndex((i) => i === b.name)) {
            return 1;
        }

        return 0;
    });
Oleg
  • 1,044
  • 1
  • 14
  • 10
2

my solution with sort :

let list = {
    "you": 100, 
    "me": 75, 
    "foo": 116, 
    "bar": 15
};

let sorted = Object.entries(list).sort((a,b) => a[1] - b[1]);

for(let element of sorted) {
    console.log(element[0]+ ": " + element[1]);
}
Rastalamm
  • 1,712
  • 3
  • 23
  • 32
2

A follow up answer to a long outdated question. I wrote two functions, one in which it sorts by keys, and the other by values, and returns the object in its sorted form in both functions. It should also work on strings as that is the reason why I am posting this (was having difficulty with some of the above on sorting by values if the values weren't numeric).

const a = {
    absolutely: "works",
    entirely: 'zen',
    best: 'player',
    average: 'joe'
}


const prop_sort = obj => {
    return Object.keys(obj)
        .sort()
        .reduce((a, v) => {
            a[v] = obj[v];
            return a; 
        }, {});
}

const value_sort = obj => {
    const ret = {}
    Object.values(obj)
        .sort()
        .forEach(val => {
            const key = Object.keys(obj).find(key => obj[key] == val)
            ret[key] = val
        })
    return ret
}

console.log(prop_sort(a))
console.log(value_sort(a))
simon
  • 854
  • 1
  • 9
  • 23
2

Here's another way to achieve this

var list = {
  "you": 100, 
  "me": 75, 
  "foo": 116, 
  "bar": 15
};

const sortedByValue = Object.fromEntries(
  Object.entries(list).sort((a, b) => {
    return a[1] - b[1];
  })
);

console.log(sortedByValue);
1

many similar and useful functions: https://github.com/shimondoodkin/groupbyfunctions/

function sortobj(obj)
{
    var keys=Object.keys(obj);
    var kva= keys.map(function(k,i)
    {
        return [k,obj[k]];
    });
    kva.sort(function(a,b){
        if(a[1]>b[1]) return -1;if(a[1]<b[1]) return 1;
        return 0
    });
    var o={}
    kva.forEach(function(a){ o[a[0]]=a[1]})
    return o;
}

function sortobjkey(obj,key)
{
    var keys=Object.keys(obj);
    var kva= keys.map(function(k,i)
    {
        return [k,obj[k]];
    });
    kva.sort(function(a,b){
        k=key;      if(a[1][k]>b[1][k]) return -1;if(a[1][k]<b[1][k]) return 1;
        return 0
    });
    var o={}
    kva.forEach(function(a){ o[a[0]]=a[1]})
    return o;
}
Shimon Doodkin
  • 4,310
  • 34
  • 37
1

Here is one more example:

function sortObject(obj) {
  var arr = [];
  var prop;
  for (prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      arr.push({
        'key': prop,
        'value': obj[prop]
      });
    }
  }
  arr.sort(function(a, b) {
    return a.value - b.value;
  });
  return arr; // returns array
}
var list = {
  car: 300,
  bike: 60,
  motorbike: 200,
  airplane: 1000,
  helicopter: 400,
  rocket: 8 * 60 * 60
};
var arr = sortObject(list);
console.log(arr);
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Mahendra Kulkarni
  • 1,437
  • 2
  • 26
  • 35
1

here is the way to get sort the object and get sorted object in return

let sortedObject = {}
sortedObject = Object.keys(yourObject).sort((a, b) => {
                        return yourObject[a] - yourObject[b] 
                    }).reduce((prev, curr, i) => {
                        prev[i] = yourObject[curr]
                        return prev
                    }, {});

you can customise your sorting function as per your requirement

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Ashutosh Ranjan
  • 642
  • 5
  • 12
1

input is object, output is object, using lodash & js built-in lib, with descending or ascending option, and does not mutate input object

eg input & output

{
  "a": 1,
  "b": 4,
  "c": 0,
  "d": 2
}
{
  "b": 4,
  "d": 2,
  "a": 1,
  "c": 0
}

The implementation

const _ = require('lodash');

const o = { a: 1, b: 4, c: 0, d: 2 };


function sortByValue(object, descending = true) {
  const { max, min } = Math;
  const selector = descending ? max : min;

  const objects = [];
  const cloned = _.clone(object);

  while (!_.isEmpty(cloned)) {
    const selectedValue = selector(...Object.values(cloned));
    const [key, value] = Object.entries(cloned).find(([, value]) => value === selectedValue);

    objects.push({ [key]: value });
    delete cloned[key];
  }

  return _.merge(...objects);
}

const o2 = sortByValue(o);
console.log(JSON.stringify(o2, null, 2));
James T.
  • 910
  • 1
  • 11
  • 24
1

To find frequency of each element and sort it by frequency/values.

let response = ["apple", "orange", "apple", "banana", "orange", "banana", "banana"];
let frequency = {};
response.forEach(function(item) {
  frequency[item] = frequency[item] ? frequency[item] + 1 : 1;
});
console.log(frequency);
let intents = Object.entries(frequency)
  .sort((a, b) => b[1] - a[1])
  .map(function(x) {
    return x[0];
  });
console.log(intents);

Outputs:

{ apple: 2, orange: 2, banana: 3 }
[ 'banana', 'apple', 'orange' ]
Vignesh G
  • 151
  • 6
  • To use the same with TypeScript, modify line .sort((a: any, b: any) => b[1] - a[1]) adding any type to variables. – Vignesh G Jul 22 '20 at 04:10
1

Another example with Object.values, sort() and the spread operator.

var paintings = {
    0: {
        title: 'Oh my!',
        year: '2020',
        price: '3000'
    },
    1: {
        title: 'Portrait V',
        year: '2021',
        price: '2000'
    },
    2: {
        title: 'The last leaf',
        year: '2005',
        price: '600'
    }
}

We transform the object into an array of objects with Object.values:

var toArray = Object.values(paintings)

Then we sort the array (by year and by price), using the spread operator to make the original array inmutable and the sort() method to sort the array:

var sortedByYear = [...toArray].sort((a, b) => a.year - b.year)
var sortedByPrice = [...toArray].sort((a, b) => a.price - b.price)

Finally, we generate the new sorted objects (again, with the spread operator to keep the original form of object of objects with a [x: number] as key):

var paintingsSortedByYear = {
    ...sortedByYear
}

var paintingsSortedByPrice = {
    ...sortedByPrice
}

Hope this could be helpful!

index
  • 31
  • 2
0

Another way to solve this:-

var res = [{"s1":5},{"s2":3},{"s3":8}].sort(function(obj1,obj2){ 
 var prop1;
 var prop2;
 for(prop in obj1) {
  prop1=prop;
 }
 for(prop in obj2) {
  prop2=prop;
 }
 //the above two for loops will iterate only once because we use it to find the key
 return obj1[prop1]-obj2[prop2];
});

//res will have the result array

vivek_nk
  • 1,590
  • 16
  • 27
0

Thank you and continue answer @Nosredna

Now that we understand object need to be converted to array then sort the array. this is useful for sorting array (or converted object to array) by string:

Object {6: Object, 7: Object, 8: Object, 9: Object, 10: Object, 11: Object, 12: Object}
   6: Object
   id: "6"
   name: "PhD"
   obe_service_type_id: "2"
   __proto__: Object
   7: Object
   id: "7"
   name: "BVC (BPTC)"
   obe_service_type_id: "2"
   __proto__: Object


    //Sort options
    var sortable = [];
    for (var vehicle in options)
    sortable.push([vehicle, options[vehicle]]);
    sortable.sort(function(a, b) {
        return a[1].name < b[1].name ? -1 : 1;
    });


    //sortable => prints  
[Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2]]
    0: Array[2]
    0: "11"
    1: Object
        id: "11"
        name: "AS/A2"
        obe_service_type_id: "2"
        __proto__: Object
        length: 2
        __proto__: Array[0]
    1: Array[2]
    0: "7"
    1: Object
        id: "7"
        name: "BVC (BPTC)"
        obe_service_type_id: "2"
        __proto__: Object
        length: 2
Fury
  • 4,643
  • 5
  • 50
  • 80
0

Try this. Even your object is not having the property based on which you are trying to sort also will get handled.

Just call it by sending property with object.

var sortObjectByProperty = function(property,object){

    console.time("Sorting");
    var  sortedList      = [];
         emptyProperty   = [];
         tempObject      = [];
         nullProperty    = [];
    $.each(object,function(index,entry){
        if(entry.hasOwnProperty(property)){
            var propertyValue = entry[property];
            if(propertyValue!="" && propertyValue!=null){
              sortedList.push({key:propertyValue.toLowerCase().trim(),value:entry});  
            }else{
                emptyProperty.push(entry);
           }
        }else{
            nullProperty.push(entry);
        }
    });

      sortedList.sort(function(a,b){
           return a.key < b.key ? -1 : 1;
         //return a.key < b.key?-1:1;   // Asc 
         //return a.key < b.key?1:-1;  // Desc
      });


    $.each(sortedList,function(key,entry){
        tempObject[tempObject.length] = entry.value;
     });

    if(emptyProperty.length>0){
        tempObject.concat(emptyProperty);
    }
    if(nullProperty.length>0){
        tempObject.concat(nullProperty);
    }
    console.timeEnd("Sorting");
    return tempObject;
}
Krypton
  • 3,337
  • 5
  • 32
  • 52
Vali Shah
  • 1,246
  • 9
  • 12
0

Using query-js you can do it like this

list.keys().select(function(k){
    return {
        key: k,
        value : list[k]
    }
}).orderBy(function(e){ return e.value;});

You can find an introductory article on query-js here

Rune FS
  • 21,497
  • 7
  • 62
  • 96
0

I made a plugin just for this, it accepts 1 arg which is an unsorted object, and returns an object which has been sorted by prop value. This will work on all 2 dimensional objects such as {"Nick": 28, "Bob": 52}...

var sloppyObj = {
    'C': 78,
    'A': 3,
    'B': 4
};

// Extend object to support sort method
function sortObj(obj) {
    "use strict";

    function Obj2Array(obj) {
        var newObj = [];
        for (var key in obj) {
            if (!obj.hasOwnProperty(key)) return;
            var value = [key, obj[key]];
            newObj.push(value);
        }
        return newObj;
    }

    var sortedArray = Obj2Array(obj).sort(function(a, b) {
        if (a[1] < b[1]) return -1;
        if (a[1] > b[1]) return 1;
        return 0;
    });

    function recreateSortedObject(targ) {
        var sortedObj = {};
        for (var i = 0; i < targ.length; i++) {
            sortedObj[targ[i][0]] = targ[i][1];
        }
        return sortedObj;
    }
    return recreateSortedObject(sortedArray);
}

var sortedObj = sortObj(sloppyObj);

alert(JSON.stringify(sortedObj));

Here is a demo of the function working as expected http://codepen.io/nicholasabrams/pen/RWRqve?editors=001

AlphaG33k
  • 1,588
  • 1
  • 12
  • 24
0

Couln't find answer above that would both work and be SMALL, and would support nested objects (not arrays), so I wrote my own one :) Works both with strings and ints.

  function sortObjectProperties(obj, sortValue){
      var keysSorted = Object.keys(obj).sort(function(a,b){return obj[a][sortValue]-obj[b][sortValue]});
      var objSorted = {};
      for(var i = 0; i < keysSorted.length; i++){
          objSorted[keysSorted[i]] = obj[keysSorted[i]];
      }
      return objSorted;
    }

Usage:

    /* sample object with unsorder properties, that we want to sort by 
    their "customValue" property */

    var objUnsorted = {
       prop1 : {
          customValue : 'ZZ'
       },
       prop2 : {
          customValue : 'AA'
       }
    }

    // call the function, passing object and property with it should be sorted out
    var objSorted = sortObjectProperties(objUnsorted, 'customValue');

    // now console.log(objSorted) will return:
    { 
       prop2 : {
          customValue : 'AA'
       },
       prop1 : {
          customValue : 'ZZ'
       } 
    }
Paul Walczewski
  • 1,316
  • 10
  • 13
  • keysSorted is sorted in ascending order of sortValue but as a javascript object is an unordered collection of properties, it doesn't make sense to attempt to order these properties – Olivier Dec 06 '17 at 11:53
0
function sortObjByValue(list){
 var sortedObj = {}
 Object.keys(list)
  .map(key => [key, list[key]])
  .sort((a,b) => a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : 0)
  .forEach(data => sortedObj[data[0]] = data[1]);
 return sortedObj;
}
sortObjByValue(list);

Github Gist Link

Ankit Sinha
  • 1,630
  • 1
  • 20
  • 19
0

I have tried in my own way

var maxSpeed = {
  car: 300, 
  bike: 60, 
  motorbike: 200, 
  airplane: 1000,
  helicopter: 400, 
  rocket: 8 * 60 * 60
};
var sorted = {}
 Object.keys(maxSpeed).sort ((a,b) => maxSpeed[a] - maxSpeed[b]).map(item => sorted[item] = maxSpeed[item]);
console.log(sorted)
Syed ss
  • 19
  • 3
-1

If I am having a Object like this ,

var dayObj = {
              "Friday":["5:00pm to 12:00am"] ,
              "Wednesday":["5:00pm to 11:00pm"],
              "Sunday":["11:00am to 11:00pm"], 
              "Thursday":["5:00pm to 11:00pm"],
              "Saturday":["11:00am to 12:00am"]
           }

want to sort it by day order,

we should have the daySorterMap first,

var daySorterMap = {
  // "sunday": 0, // << if sunday is first day of week
  "Monday": 1,
  "Tuesday": 2,
  "Wednesday": 3,
  "Thursday": 4,
  "Friday": 5,
  "Saturday": 6,
  "Sunday": 7
}

Initiate a separate Object sortedDayObj,

var sortedDayObj={};
Object.keys(dayObj)
.sort((a,b) => daySorterMap[a] - daySorterMap[b])
.forEach(value=>sortedDayObj[value]= dayObj[value])

You can return the sortedDayObj

Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
  • this does not answer OP's question at all – notnavindu Dec 18 '19 at 12:44
  • @notnavindu .. Yeah may be that doesnt answer it all, But do have a simpler solution for it , ` let toSort = {a:2323, b: 14, c: 799} let sorted = Object.entries(toSort ).sort((a,b)=> a[1]-b[1]) output: [ [ "b", 14 ], [ "c", 799 ], [ "a", 2323 ] ] ` – Remi Prasanna Feb 12 '20 at 06:54
-2

Below is the working code

var list = {
  "you": 100, 
  "me": 75, 
  "foo": 116, 
  "bar": 15
};
var sortArray = [];

// convert the list to array of key and value pair
for(let  i in list){
    sortArray.push({key : i, value:list[i]});
}

//console.log(sortArray);
// sort the array using value.
sortArray.sort(function(a,b){
return a.value - b.value;
});

//console.log(sortArray);

// now create a newList of required format.
let newList={};
for(let i in sortArray){
newList[sortArray[i].key] = sortArray[i].value;
}

console.log(newList);
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31423253) – Ethan McTague Apr 01 '22 at 17:49
  • @EthanMcTague - Why do you think the above doesn't work? – Narmada Muralikrishnan Apr 26 '23 at 09:31