I have a JS object defined as this {0: 3, 2: 2, 4: 1}
, and I want to sort only the values, and leave the keys in tact. What I mean is that after the object is sorted, the end result should be {0: 1, 2: 2, 4: 3}
, so only the values change their places and not the keys.
I have the following code segment:
let list = {0: 3, 2: 2, 4: 1};
Object.keys(list)
.sort((a, b) => list[a]-list[b])
.reduce((obj, key) => ({
...obj,
[key]: list[key]
}), {});
But, it doesn't seem to work. In fact, it doesn't seem to sort it at all. Any ideas how to achieve what I want in JS?