Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  116] [ 1]  / answers: 1 / hits: 22321  / 7 Years ago, thu, may 4, 2017, 12:00:00

Say you have the following object in JS:



let obj = {a: 24, b: 12, c:21; d:15};


How can 'obj' be transformed into an array of the keys of the object, sorted by the values?


More From » javascript

 Answers
21



let obj = {a: 24, b: 12, c:21, d:15};

// Get an array of the keys:
let keys = Object.keys(obj);

// Then sort by using the keys to lookup the values in the original object:
keys.sort(function(a, b) { return obj[a] - obj[b] });

console.log(keys);





Note that the above could be done in one line if desired with Object.keys(obj).sort(...). The simple .sort() comparator function shown will work for numeric values only (swap a and b to sort in the opposite direction), but since that's what's in the question I assume it's fine...


[#57906] Tuesday, May 2, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
calicinthias

Total Points: 447
Total Questions: 101
Total Answers: 118

Location: Botswana
Member since Sat, Dec 31, 2022
1 Year ago
calicinthias questions
Sun, Jan 2, 22, 00:00, 2 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Mon, Aug 10, 20, 00:00, 4 Years ago
;