Skip to content

Instantly share code, notes, and snippets.

@sidneisimeao
Created August 17, 2018 12:46
Show Gist options
  • Save sidneisimeao/88adc9811297f200e583d4663fd762ba to your computer and use it in GitHub Desktop.
Save sidneisimeao/88adc9811297f200e583d4663fd762ba to your computer and use it in GitHub Desktop.
const data = [
{
name: "Alexandre",
city: "MG",
age: "45"
},
{
name: "Ricardo",
city: "MG",
age: "32"
},
{
name: "Igor",
city: "RJ",
age: "43"
},
{
name: "Sidnei",
city: "MG",
age: "32"
},
{
name: "Julio",
city: "SP",
age: "30"
},
{
name: "Antonio",
city: "SP",
age: "30"
}
];
const groupedData = data.reduce((grouped, { age, city, name }) => {
// Agrupa por Cidade
(city in grouped == false) ? grouped[city] = {} : null;
// Agrupa por Idade
(age in grouped[city] == false) ? grouped[city][age] = [] : null;
// Adiciona o Nome a matriz
grouped[city][age].push(name) ;
return grouped;
}, {});
console.log(groupedData);
@sidneisimeao
Copy link
Author

O dev Matheus Valeriano propos uma solução melhor:

const groupCity = (grouped, city) => ({
...grouped,
[city]: grouped[city] || {}
})

const groupAges = (grouped, city, age, name) => (
{
...(grouped[city] || {}),
[age]: [...(grouped[city][age] || []), name]
}
)

const groupedData = data.reduce((grouped, { age, city, name }) => {
grouped = groupCity(grouped, city)
grouped[city] = groupAges(grouped, city, age, name)
return grouped;
}, {});

console.log(groupedData);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment