HomeAbout MePublicationsContact

Group Array of Objects by Key

By Suresh Kumar Mukhiya
Published in Frontend Cheetseat
October 05, 2021
1 min read

Problem:

Given an arry of objects, we need to group objects by any key.

Input:

const arrayObjects = [
   {
      "Phase":"Phase 1",
      "Step":"Step 1",
      "Task":"Task 1",
      "Value":"5"
   },
   {
      "Phase":"Phase 1",
      "Step":"Step 1",
      "Task":"Task 2",
      "Value":"10"
   },
   {
      "Phase":"Phase 1",
      "Step":"Step 2",
      "Task":"Task 1",
      "Value":"15"
   },
   {
      "Phase":"Phase 1",
      "Step":"Step 2",
      "Task":"Task 2",
      "Value":"20"
   },
   {
      "Phase":"Phase 2",
      "Step":"Step 1",
      "Task":"Task 1",
      "Value":"25"
   },
   {
      "Phase":"Phase 2",
      "Step":"Step 1",
      "Task":"Task 2",
      "Value":"30"
   },
   {
      "Phase":"Phase 2",
      "Step":"Step 2",
      "Task":"Task 1",
      "Value":"35"
   },
   {
      "Phase":"Phase 2",
      "Step":"Step 2",
      "Task":"Task 2",
      "Value":"40"
   }
];

Expected Output:

{
  "Task 1": [
    {
      "Phase": "Phase 1",
      "Step": "Step 1",
      "Task": "Task 1",
      "Value": "5"
    },
    {
      "Phase": "Phase 1",
      "Step": "Step 2",
      "Task": "Task 1",
      "Value": "15"
    },
    {
      "Phase": "Phase 2",
      "Step": "Step 1",
      "Task": "Task 1",
      "Value": "25"
    },
    {
      "Phase": "Phase 2",
      "Step": "Step 2",
      "Task": "Task 1",
      "Value": "35"
    }
  ],
  "Task 2": [
    {
      "Phase": "Phase 1",
      "Step": "Step 1",
      "Task": "Task 2",
      "Value": "10"
    },
    {
      "Phase": "Phase 1",
      "Step": "Step 2",
      "Task": "Task 2",
      "Value": "20"
    },
    {
      "Phase": "Phase 2",
      "Step": "Step 1",
      "Task": "Task 2",
      "Value": "30"
    },
    {
      "Phase": "Phase 2",
      "Step": "Step 2",
      "Task": "Task 2",
      "Value": "40"
    }
  ]
}

Solution:

const groupBy = (items, key) =>
  items.reduce(
    (result, item) => ({
      ...result,
      [item[key]]: [...(result[item[key]] || []), item]
    }),
    {}
  )

Tags

arrayJavaScript
Previous Article
Difference between software architecture and software design
Suresh Kumar Mukhiya

Suresh Kumar Mukhiya

Software Engineer

Topics

Artificial Intelligence
Frontend Cheetseat
My Philosophy
Paper Review
Research Methods
Software Architecture

Related Posts

Fastest way to check if an object is empty
October 27, 2021
1 min
© 2021, All Rights Reserved.

Quick Links

PublicationsAbout meContact Me

Social Media