Skip to content

Instantly share code, notes, and snippets.

@tuliopaim
Last active November 26, 2020 02:43
Show Gist options
  • Select an option

  • Save tuliopaim/2af77253e799caffff9ac76afd852406 to your computer and use it in GitHub Desktop.

Select an option

Save tuliopaim/2af77253e799caffff9ac76afd852406 to your computer and use it in GitHub Desktop.
Função para agrupar uma lista em multiplas listas por propriedade, similar ao .GroupBy() do Linq no C#
function AgruparPorPropriedade(arr, propName) {
var group = [];
arr.forEach(item => {
if (!group[item[propName]])
group[item[propName]] = arr.filter(i => i[propName] === item[propName]);
});
return group;
}
let listaStatus = [
{ Id: 1, Status: 'Aberto', Name: "Túlio" },
{ Id: 2, Status: 'Fechado', Name: "Raul" },
{ Id: 3, Status: 'Pendente', Name: "Lucas" },
{ Id: 4, Status: 'Maluco', Name: "Luis" },
{ Id: 5, Status: 'Pendente', Name: "Ygor" },
{ Id: 6, Status: 'Pendente', Name: "Daniel" },
{ Id: 7, Status: 'Fechado', Name: "Valmir" },
{ Id: 8, Status: 'Aberto', Name: "João" },
];
var listasPorStatus = AgruparPorPropriedade(listaStatus, 'Status');
console.log();
listasPorStatus.forEach(lista => {
console.log(lista.Key + " - " + lista.Value.length);
lista.Value.forEach(i => console.log(i));
console.log();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment