Created
August 17, 2018 12:46
-
-
Save sidneisimeao/88adc9811297f200e583d4663fd762ba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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);