Open In App

How to Regroup JSON array in JavaScript

Last Updated : 18 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Regrouping JSON arrays in JavaScript is crucial for organizing data efficiently, simplifying data management tasks, and ensuring better data integration across systems. Here, we will regroup JSON arrays in JavaScript in two methods to achieve this using the reduce method and an iterative approach.

Using Iterative Method

In this approach, The function begins by initializing an empty object called "group" to store regrouped data. It iterates over each item in the jsonArray using forEach(). Each item's category property is checked, and if a corresponding key doesn't exist in the "group" object, one is created with an empty array. Items are then pushed into their respective category arrays. Finally, the function returns the "group" object with regrouped data based on categories.

Example: In this example regrouping JSON array in JavaScript using a loop-based method.


Output
{
  A: [
    { id: 1, category: 'A' },
    { id: 3, category: 'A' },
    { id: 6, category: 'A' }
  ],
  B: [ { id: 2, category: 'B' }, { id: 5, category: 'B' } ],
  C: [ { id: 4, category: 'C' } ]
}

Using Array.reduce()

In this approach, The reduce() method initializes an empty object as the accumulator. It iterates over each item in the jsonArray, grouping them by their category property. If a category key doesn't exist, it creates one with an empty array. It then pushes items into their respective category arrays. Finally, it returns the grouped object containing the regrouped data.

Example: The below example shows a regrouped JSON array in JavaScript Using Array.reduce().


Output
{
  A: [
    { id: 1, category: 'A' },
    { id: 3, category: 'A' },
    { id: 6, category: 'A' }
  ],
  B: [ { id: 2, category: 'B' }, { id: 5, category: 'B' } ],
  C: [ { id: 4, category: 'C' } ]
}

Next Article

Similar Reads