Home > Web Front-end > JS Tutorial > How can I group an array of objects by a specific property and consolidate other properties into arrays?

How can I group an array of objects by a specific property and consolidate other properties into arrays?

Mary-Kate Olsen
Release: 2024-12-15 12:08:14
Original
465 people have browsed it

How can I group an array of objects by a specific property and consolidate other properties into arrays?

Grouping Array Items by Object Property

Given an array of objects with group and color properties, the goal is to group the items by their group values, consolidating the color values for each group.

Problem

The provided array looks like this:

myArray = [
  {group: "one", color: "red"},
  {group: "two", color: "blue"},
  {group: "one", color: "green"},
  {group: "one", color: "black"}
]
Copy after login

The desired output is an array like this:

myArray = [
  {group: "one", color: ["red", "green", "black"]},
  {group: "two", color: ["blue"]}
]
Copy after login

Solution

  1. Create a Map of Group Names to Values: Use the reduce() method to create a mapping from group names to arrays of colors.
  2. Transform into Desired Format: Create a new array by iterating over the map's keys and creating an object for each group, with its group property set to the key and its color property set to the array of colors associated with that key.

Below is a JavaScript implementation:

var myArray = [
    {group: "one", color: "red"},
    {group: "two", color: "blue"},
    {group: "one", color: "green"},
    {group: "one", color: "black"}
];

var group_to_values = myArray.reduce(function (obj, item) {
    obj[item.group] = obj[item.group] || [];
    obj[item.group].push(item.color);
    return obj;
}, {});

var groups = Object.keys(group_to_values).map(function (key) {
    return {group: key, color: group_to_values[key]};
});

console.log("groups:");
console.log(JSON.stringify(groups, null, 4));
Copy after login

This code creates the desired output, with the items grouped by their group property and their color values consolidated into arrays.

The above is the detailed content of How can I group an array of objects by a specific property and consolidate other properties into arrays?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template