0

Assume the following objects

let oldArr = [
  { a: 1 },
  { a: 2 },
  { a: 3 },
  { b: 1 },
  { b: 2 },
  { c: 1 }
]

Desired result

let newArr = [
  [
    { a: 1 },
    { a: 2 },
    { a: 3 },
  ],
  [
    { b: 1 },
    { b: 2 },
  ],
  [
    { c: 1 }
  ],
]

I try to use lodash, I see the partition function but it only splits the arrays into 2 groups. The groupBy groups it into an object by keys. Is there any good way? hope to get everyone's help, thank you!

Ori Drori
  • 183,571
  • 29
  • 224
  • 209
nline BGO
  • 59
  • 6

3 Answers3

0

Simply like this:

let oldArr = [
  { a: 1 },
  { a: 2 },
  { a: 3 },
  { b: 1 },
  { b: 2 },
  { c: 1 }
]

let objects = {};

for (let item of oldArr) {
  // get key
  let key = Object.keys(item)[0];
  // check if this key added before
  if (!objects[key]) objects[key] = [];
  // push this object
  objects[key].push(item);
}

let newArr = Object.values(objects);

console.log(newArr)

But you should be sure that every object in oldArr has only one key.

Nimer Awad
  • 3,967
  • 3
  • 17
  • 31
  • 1
    [How do I create a runnable stack snippet?](https://meta.stackoverflow.com/questions/358992) – adiga Dec 26 '19 at 09:27
0

you can do this using Object.keys, Object.values and Array.reduce

let oldArr = [
  { a: 1 },
  { a: 2 },
  { a: 3 },
  { b: 1 },
  { b: 2 },
  { c: 1 },
  { a: 4, c: 2 }
]

let newArr = 
  // drop the keys of the object created by the reduce
  Object.values(
    // for each object in the array
    oldArr.reduce((acc, el) => {
      // for each keys in the object
      Object.keys(el).forEach(key => {
        // add the object to the group of objects with this key
        acc[key] = acc[key] || []
        acc[key].push(el)
      })
      return acc
    }, {})
  )

console.log(newArr)

if an object in the input have multiple keys it will go to each group in the output

jonatjano
  • 3,576
  • 1
  • 15
  • 20
0

you can use like that

let oldArr = [
  { a: 1 },
  { a: 2 },
  { a: 3 },
  { b: 1 },
  { b: 2 },
  { c: 1 }
];
let newArr = {};
oldArr.forEach((i)=>{
  let key = Object.keys(i)[0];
  newArr[key] = newArr[key] || [];
  newArr[key].push(i);
});
newArr = Object.values(newArr);
console.log(newArr);
Tonmoy Nandy
  • 371
  • 4
  • 9