I need help organizing an object
{a: 1, b: 20, c: 3, d: 4, e: 1, f: 4}
into the following format {a: 1, e: 1, c: 3, d: 4, f: 4, b:20}
(sorting the object numerically in ascending order) using a specific set of steps. Here are the steps I have outlined:
Define a function named 'sort' that takes an object as an argument, and includes an empty array named 'arr' within it.
Iterate through the object and push each key-value pair as an array into 'arr'.
Sort the array numerically based on the object values.
Create an empty object named 'newObj'.
Iterate through the array and assign the key and value to 'newObj' accordingly.
Return 'newObj'.
I have started writing the code but I am encountering issues, particularly with the sorting part.
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
}
What improvements can I make to this code to ensure the function works correctly?