Posts Use js reduce to group array of objects by key
Post
Cancel

Use js reduce to group array of objects by key

This will create a new object with each gender grouped by key using the reduce function.

Array of objects to be grouped by gender:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const arr = [
  {
    id: 1,
    name: "Lisa",
    gender: "female"
  },
  {
    id: 2,
    name: "Tim",
    gender: "male"
  },
  {
    id: 3,
    name: "Karl",
    gender: "male"
  },
  {
    id: 4,
    name: "Sarah",
    gender: "female"
  },
  {
    id: 5,
    name: "Evelyn",
    gender: "female"
  }
];

Code:

1
2
3
4
5
6
7
8
9
const grouped = arr.reduce((acc, curr) => {
  // Creates a new key with an empty array if it doesn't exist.
  acc[curr.gender] = acc[curr.gender] || []; 

  // Push the content of that object to the newly created key
  acc[curr.gender].push(curr);

  return acc;
}, {}); // Start with an empty object

Output, an object grouped by key:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const groupedByKey {
  female: [
    {
      id: 1,
      name: "Lisa",
      gender: "female",
    },
    {
      id: 4,
      name: "Sarah",
      gender: "female",
    },
    {
      id: 5,
      name: "Evelyn",
      gender: "female",
    },
  ],
  male: [
    {
      id: 2,
      name: "Tim",
      gender: "male",
    },
    {
      id: 3,
      name: "Karl",
      gender: "male",
    },
  ],
};
This post is licensed under CC BY 4.0 by the author.