I want to manipulate an object {a: 1, b: 20, c: 3, d: 4, e: 1, f: 4}
into this {a: 1, e: 1, c: 3, d: 4, f: 4, b:20}
(sorting the object numerically in ascending order) in these specific steps (I am aware that there must be easier, more advanced ways):
Defining a function called 'sort' which takes an object as argument and inside it declaring an empty array called 'arr'.
Looping inside the object and for each iteration push an array which contains the key and the value to 'arr'.
Sorting the array numerically by the object value (position one in our nested arrays)
Creating an empty object called 'newObj'.
Looping through the array and for each iteration assign the first and second element as the key and value respectively to our 'newobJ'
Returning the 'newObj'.
This is what I have so far. The code has hickups at the sorting parts but maybe also other things I am not yet aware of.
function sort(object) {
var arr = []
var newObj = {}
Object.entries(object).forEach(function(element, index) {
arr.push(element)
})
arr[index][1].sort(function(a, b){return b-a});
arr.forEach(function([key, value], index) {
newObj[key] = value
})
return newObj
}
How do I need to improve my code to make the function work?