I'm trying to sort an object and rebuild it based on highest to lowest values in Javascript. I've built a function which takes an array of numbers, counts them adds them up and then creates an object, my function for sorting doesn't seem to be working correctly,
const numbersToCount = [10, 10, 10, 5, 4, 3, 2, 2, 1]
function sort () {
var counts = {}
for (var i = 0; i < numbersToCount.length; i++) {
var num = numbersToCount[i];
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
var numbersToSort = []
for (var sort in counts) {
numbersToSort.push([sort , counts[sort]])
}
numbersToSort.sort((a, b) => {
return a[1] - b[1]
})
counts = {}
numbersToSort.forEach((item) => {
counts[item[0]]=item[1]
})
console.log(counts)
}
Currently, counts
would output initally:
{
'1': 1,
'2': 2,
'3': 1,
'4': 1,
'5': 1,
'10': 3
}