-1

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)
Danilo
  • 11
  • 1
  • Please translate the title, too – ChrisGPT was on strike Aug 19 '23 at 22:35
  • 1
    Object keys don't have an intrinsic ordering (that's defined by the runtime implementation as an internal detail) — but the ways that an object's keys are iterated is well-defined. Similarly, serialization of an object for display (e.g. `console.log`) is implementation-specific, and a number of implementations will display an object's keys in string lexicographic order. Try iterating the keys and values using [`Object.entries(peopleCounterByAge)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries). – jsejcksn Aug 19 '23 at 23:02
  • 1
    [^](https://stackoverflow.com/questions/76937228/question-about-the-reduce-method-to-create-an-object-from-an-array#comment135630254_76937228) See [Does ES6 introduce a well-defined order of enumeration for object properties?](https://stackoverflow.com/q/30076219/438273) – jsejcksn Aug 19 '23 at 23:07
  • 1
    For this specific task, see also [`Object.groupby` in tc39/proposal-array-grouping](https://github.com/tc39/proposal-array-grouping) ([`core-js` implementation](https://github.com/zloirock/core-js/blob/v3.32.1/packages/core-js/modules/esnext.object.group-by.js)) – jsejcksn Aug 19 '23 at 23:08

0 Answers0