From an array of people objects, I want to return an object with a counter of people by age. When using the reduce method, it assembles my object with the keys of the properties in ascending order and not in the order of the loop. Why does this happen? And how could I change this ordering form?
const people = [
{name : 'Daniel', age: 38},
{name : 'Maria', age: 29},
{name : 'Marta', age: 29}
]
const peopleCounterByAge = people.reduce((acc, person) => {
if(acc[person.age]){
acc[person.age].push(person.name)
}else{
acc[person.age] = []
acc[person.age].push(person.name)
}
return acc
}, {})
console.log(peopleCounterByAge)