I want to find occurrences of number in an array and then display the numbers and the occurrences with the numbers sorted in an ascending order like this:
let arr = [9,-10,2,9,6,1,2,10,-8,-10,2,9,6,1];
// {'-10': 2, '-8': 1, '1': 2, '2': 3, '6': 2, '9': 3, '10': 1}
I've found the occurrences of each number in the array by storing them in an object. When I tried console.log the numCount, all the numbers are sorted in an ascending order except for the negative numbers.
/*Find occurrences*/
let numCount = {};
for(let num of arr){
numCount[num] = numCount[num] ? numCount[num] + 1 : 1;
}
console.log(numCount);
//{ '1': 2, '2': 3, '6': 2, '9': 3, '10': 1, '-10': 2, '-8': 1 }
I look it up on how to sort object and it seems like the way to do it is by storing them in an array and then sort it. So that's what I tried:
/*Store them in array and then sort it*/
let sortedArray = [];
for(let item in numCount){
sortedArray.push([item, numCount[item]]);
}
sortedArray.sort(function(a,b){
return a[0] - b[0];
});
/*
console.log(sortedArray);
[
[ '-10', 2 ],
[ '-8', 1 ],
[ '1', 2 ],
[ '2', 3 ],
[ '6', 2 ],
[ '9', 3 ],
[ '10', 1 ]
]
*/
This next method supposed to display them in an object sorted in ascending order but when I tried it, it displayed them with the negative numbers in the end of that object just like in the beginning. So this is the part where I'm stuck.
let sortedObject = {};
sortedArray.forEach(function(item){
sortedObject[item[0]] = item[1];
})
/*console.log(sortedObject);
{ '1': 2, '2': 3, '6': 2, '9': 3, '10': 1, '-10': 2, '-8': 1 }
*/
Full code:
let arr = [9,-10,2,9,6,1,2,10,-8,-10,2,9,6,1];
/*Find occurrences*/
let numCount = {};
for(let num of arr){
numCount[num] = numCount[num] ? numCount[num] + 1 : 1;
}
/*Store them in array and then sort it*/
let sortedArray = [];
for(let item in numCount){
sortedArray.push([item, numCount[item]]);
}
sortedArray.sort(function(a,b){
return a[0] - b[0];
});
let sortedObject = {};
sortedArray.forEach(function(item){
sortedObject[item[0]] = item[1];
})
console.log(sortedObject);