-1

I have an array of objects with common properties. For example

[{color:"red",name:"basher"},
 {color:"blue", name:"tony"},
 {color:"red",name:"bobo"},
 {color:"blue",name:"pina"}
]

The desired output is an array of arrays like the following -

[
    [{color:"red",name:"basher"},{color:"red",name:"bobo"}],
    [{color:"blue",name:"tony"},{color:"blue",name:"pina"}]
]

I've found this question slightly similar question but it splits the array into objects with keys. I dont want the keys. I simply want to split the array of objects into an array of arrays each containing the objects with similar properties.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Nizar
  • 737
  • 6
  • 15
  • After you split into an object with keys, you can use `Object.values()` to get an array of the values without the keys. – Barmar Apr 23 '21 at 16:14

3 Answers3

1

After grouping, you just have to grab the values

const array = [
  { color: "red", name: "basher" },
  { color: "blue", name: "tony" },
  { color: "red", name: "bobo" },
  { color: "blue", name: "pina" },
]

const res = Object.values(
  array.reduce((acc, el) => {
    if (acc[el.color] !== undefined) {
      acc[el.color].push(el)
    } else {
      acc[el.color] = [el]
    }
    return acc
  }, {})
)

console.log(res)

Object.values()

hgb123
  • 13,869
  • 3
  • 20
  • 38
1

The principles of groupBy are basically the same ....you need an object or Map that uses the common values as keys, then group/process the values for that key. Then get all the Map or Object values as result

Example using Map

const data = [{color:"red",name:"basher"},{color:"blue", name:"tony"},{color:"red",name:"bobo"},{color:"blue",name:"pina"}],

group = data.reduce((a,c) => a.set( c.color, [...(a.get(c.color) || []) ,c]) ,new Map),

res = [...group.values()]
console.log(res)
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

const arr = [{
  color: "red",
  name: "basher"
}, {
  color: "blue",
  name: "tony"
}, {
  color: "red",
  name: "bobo"
}, {
  color: "blue",
  name: "pina"
}];

const groupObjects = (arr, prop) => {
  const result = [];
  const values = [...new Set(arr.map(obj => obj[prop]))];
  values.forEach(value => result.push(arr.filter(obj => obj[prop] === value)));
  return result;
};

console.log(groupObjects(arr, 'color'));
Alyks
  • 41
  • 3