Home > Web Front-end > JS Tutorial > How Can I Efficiently Group an Array of Objects in JavaScript Using a Vanilla Approach?

How Can I Efficiently Group an Array of Objects in JavaScript Using a Vanilla Approach?

Susan Sarandon
Release: 2024-12-30 12:31:13
Original
359 people have browsed it

How Can I Efficiently Group an Array of Objects in JavaScript Using a Vanilla Approach?

Efficient GroupBy Method for Arrays of Objects

Grouping objects based on common properties is a common task in data processing. This snippet provides an efficient solution to group objects in an array using a vanilla JavaScript approach.

Why Avoid Underscore.js?

While Underscore.js offers a groupBy function, its implementation may not be suitable if you require "merged" results rather than separate groups.

Custom Vanilla JS GroupBy

The following script defines a groupBy function that operates on an array of objects:

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};
Copy after login

Example Usage

To group objects by "Phase":

const data = [
  { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
  ...
];
const groupedByPhase = groupBy(data, 'Phase');
Copy after login

groupedByPhase will contain:

{
  "Phase 1": [
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
    ...
  ],
  "Phase 2": [
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
    ...
  ]
}
Copy after login

To group further by "Step":

const groupedByPhaseStep = _(groupedByPhase).values().map(phase => {
  return groupBy(phase, 'Step');
}).value();
Copy after login

groupedByPhaseStep will contain:

[
  {
    "Phase": "Phase 1",
    "Step": "Step 1",
    "Value": 15
  },
  ...
]
Copy after login

The above is the detailed content of How Can I Efficiently Group an Array of Objects in JavaScript Using a Vanilla Approach?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template