0

I would like to group objects by key mod. I have this array:

const testArray = [
  {cor: 'yellow', peso: 2, seq: 1, mod: 'normal'},
  {cor: 'yellow', peso: 2, seq: 2, mod: 'normal'},
  {cor: 'yellow', peso: 3, seq: 3, mod: 'abstract'},
  {cor: 'verde', peso: 5, seq: 4, mod: 'normal'},
  {cor: 'yellow', peso: 4, seq: 5, mod: 'abstract'},
  {cor: 'green', peso: 8, seq: 6, mod: 'abstract'},
  {cor: 'yellow', peso: 9, seq: 7, mod: 'normal'}
]

and i expect to create a new array with this objects like this:

const groupArray = [
  [
    {cor: 'yellow', peso: 2, seq: 1, mod: 'normal'},
    {cor: 'yellow', peso: 2, seq: 2, mod: 'normal'},
    {cor: 'yellow', peso: 9, seq: 7, mod: 'normal'}
  ],
  [
    {cor: 'yellow', peso: 4, seq: 5, mod: 'abstract'},
    {cor: 'yellow', peso: 3, seq: 3, mod: 'abstract'},
  ]
];

Someone could help me? I tried with .map anda .filter but does't works.

Sergio RBJ
  • 43
  • 2
  • 8

2 Answers2

0

Are you sure that you tried the filter method?

This is how you would use it to solve this problem.

let newArr = [
  testArray.filter((thing) => thing.mod === 'normal'),
  testArray.filter((thing) => thing.mod === 'abstract')
];
marcusshep
  • 1,916
  • 2
  • 18
  • 31
0

You can use the map function with Set, like this:

const testArray = [
  {cor: 'yellow', peso: 2, seq: 1, mod: 'normal'},
  {cor: 'yellow', peso: 2, seq: 2, mod: 'normal'},
  {cor: 'yellow', peso: 3, seq: 3, mod: 'abstract'},
  {cor: 'verde', peso: 5, seq: 4, mod: 'normal'},
  {cor: 'yellow', peso: 4, seq: 5, mod: 'abstract'},
  {cor: 'green', peso: 8, seq: 6, mod: 'abstract'},
  {cor: 'yellow', peso: 9, seq: 7, mod: 'normal'}
];

var mods = [...new Set(testArray.map(x => x.mod))];

var output = [];

mods.forEach(mod => output.push(testArray.filter(item => item.mod === mod)));

console.log(output);
Tân
  • 1
  • 15
  • 56
  • 102