In my quest to locate occurrences of numbers within an array, I aimed to display the numbers and their respective frequencies in ascending order. Here is what I was trying to achieve:
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}
To accomplish this task, I stored the occurrences of each number in an object. However, upon logging the numCount object, I noticed that while all the numbers were sorted in ascending order, the negative numbers did not follow suit.
/*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 researched how to sort objects and learned that one method involved storing them in an array and then sorting it. So, I attempted the following approach:
/*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 ]
]
*/
However, the resulting sortedObject displayed the negative numbers at the end, similar to the initial state. This is the hurdle I am currently facing.
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 }
*/
Here is the full code snippet:
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);