-2

This is somewhat complex for me to put into words properly, so I'll just drop an example of what I'm trying to do in terms of input and expected output below. I've tried a few things but they seem to be way more complex than needed, result in duplication issues, or flat out don't work. Thanks ahead of time for any help people can provide. And if there's already a post that answers this question, I am sorry and I'll gladly take that link - as I said, it's difficult to put this into words.

Input: Array of Objects

Ex:

[
    {prop: 1},
    {prop: 1},
    {prop: 2},
    {prop: 3},
    {prop: 2}
]

OUTPUT: Array of arrays where all objects with some matching property are grouped. Ex:

[
    [{prop: 1}, {prop: 1}],
    [{prop: 2},{prop:2}],
    [{prop:3}]
]
Jordy337
  • 390
  • 2
  • 5
  • 17
  • Hi, could you please also add your attempt at solving the problem (even if it doesn't work), it will help us show you where you went wrong / save our time from having to write all the code from scratch – Nick Parsons Dec 02 '20 at 00:56

1 Answers1

1

Simple reduce loop with an object

var arr = [
    {prop: 1},
    {prop: 1},
    {prop: 2},
    {prop: 3},
    {prop: 2}
]

const result = Object.values(arr.reduce((acc, item) => {
 acc[item.prop] = acc[item.prop] || [];
 acc[item.prop].push(item);
 return acc;
}, {}));

console.log(result);
epascarello
  • 204,599
  • 20
  • 195
  • 236