Skip to content
Home » Program to Group Data Based on Property in JavaScript

Program to Group Data Based on Property in JavaScript

This program is a simple JavaScript code snippet that allows you to group an array of data based on a given property. It makes use of the reduce function, a built-in method in JavaScript that applies a function to each element in an array, resulting in a single output value. In this case, the program groups the data based on a specified property and returns an object with the grouped data.

Code

//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

export const groupData = (data: any[], property: string) => {
  return data.reduce(function (acc, obj) {
    let key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
};

// returns an object

Code Explanation

The provided code snippet begins by declaring a function named groupData, which takes two parameters: data, an array of any type, and property, a string representing the property to group the data by. The function returns the grouped data as an object.

Inside the groupData function, the reduce method is used. The reduce function takes a callback function as its first argument and an optional initial value as its second argument.

The callback function receives an accumulator (acc) and the current object (obj) as its parameters. It first extracts the value of the specified property (key) from the current object.

Next, it checks if the accumulator object (acc) already has a property with the extracted value. If not, it initializes an empty array as the value for that property.

Finally, it pushes the current object into the corresponding array in the accumulator object.

The reduce function continues to iterate through each object in the data array, updating the accumulator object accordingly. Once all objects have been processed, the reduce function returns the final accumulator object.

Overall, this code snippet provides a convenient way to group data based on a specific property in JavaScript, allowing for easier data manipulation and analysis.

Example usage:

javascript
const data = [
  { name: 'John', age: 25, city: 'New York' },
  { name: 'Jane', age: 30, city: 'London' },
  { name: 'Bob', age: 35, city: 'New York' },
  { name: 'Alice', age: 28, city: 'London' },
];

const groupedData = groupData(data, ‘city’);

console.log(groupedData);

Output:

{
  "New York": [
    { "name": "John", "age": 25, "city": "New York" },
    { "name": "Bob", "age": 35, "city": "New York" }
  ],
  "London": [
    { "name": "Jane", "age": 30, "city": "London" },
    { "name": "Alice", "age": 28, "city": "London" }
  ]
}

In this example, we have an array of objects representing people with their names, ages, and cities. We use the groupData function to group the objects based on the city property. The resulting grouped data is then printed to the console.

Conclusion

The provided JavaScript code snippet demonstrates an efficient way to group data based on a specified property. By using the `reduce` function, the program reduces multiple objects into a single object containing the grouped data. This functionality can be useful in a wide range of scenarios, such as analyzing data, generating reports, or organizing information.

Also checkout the following codes.


Program to Create Demand from Idea in ServiceNow
How to Get the Date One Month Ago in JavaScript – Program to Calculate the Date