I am confused about how JavaScript seems to implement some sort of default sorting when the keys of an object are initially inserted as numbers (before being typecast as strings):
let myObj = {2: 'ant', 3: 'bee', 1: 'cat', shark: 'shark', mouse: 'mouse'}
console.log(myObj); // { '1': 'cat', '2': 'ant', '3': 'bee', shark: 'shark', mouse: 'mouse' }
// Expected: { '2': 'ant', '3': 'bee', '1': 'cat', shark: 'shark', mouse: 'mouse' }
The context I first noticed this was when building a "frequency object" for an array of numbers:
function frequencies(nums) {
return nums.reduce((acc, num) => {
acc[num] = (++acc[num] || 1);
return acc;
}, {});
}
const stringsExample = frequencies(['cat', 'dog', 'cow', 'cow', 'dog', 'ant', 3, 1, 2]);
console.log(stringsExample); // { '1': 1, '2': 1, '3': 1, cat: 1, dog: 2, cow: 2, ant: 1 }
// Expected: { cat: 1, dog: 2, cow: 2, ant: 1, '3': 1, '1': 1, '2': 1 }
const numbersExample = frequencies([5,5,5,3,4,5,6,2]);
console.log(numbersExample); // { '2': 1, '3': 1, '4': 1, '5': 4, '6': 1 }
// Expected: { '5': 4, '3': 1, '4': 1, '6': 1, '2': 1 }
I have not found anything online that explains what causes this behavior. Can anyone explain what is happening here?