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
Susan SarandonOriginal
2024-12-30 12:31:13289browse

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;
  }, {});
};

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');

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" },
    ...
  ]
}

To group further by "Step":

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

groupedByPhaseStep will contain:

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

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:
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