In order to better understand how to manipulate objects, I'm trying to sort an object based on its values.
eg.
let obj = {
1: 5,
2: 4,
3: 200,
4: 3,
5: 1
}
and I want an output of
{
3: 200,
1: 5,
2: 4,
4: 3,
5: 1
}
I've looped through the object and added its key value pairs into a new array, which I then sort by the values.
the new array looks like this
[
[3, 200],
[1, 5],
[2, 4],
[4, 3],
[5, 1]
]
I then loop through this array and create a new object from it, but it's coming out as
{ 1: 5, 2: 4, 3: 200, 4: 3, 5: 1 }
why?
let obj = {
1: 5,
2: 4,
3: 200,
4: 3,
5: 1
}
const sortObj = o => {
const arr = [];
const _obj = {};
for (const v in o) arr.push([v, o[v]]);
arr.sort((a, b) => b[1] - a[1]);
for (const v of arr) {
console.log(v);
/*
[
[3, 200],
[1, 5],
[2, 4],
[4, 3],
[5, 1]
]
*/
const [key, val] = v;
console.log(key, val);
_obj[key] = val;
}
return _obj;
}
console.log(sortObj(obj));