Home > Web Front-end > JS Tutorial > How to Group Array Items by Object Properties in JavaScript?

How to Group Array Items by Object Properties in JavaScript?

DDD
Release: 2024-12-31 01:53:12
Original
835 people have browsed it

How to Group Array Items by Object Properties in JavaScript?

Group Array Items by Object Properties

In your scenario, you wish to consolidate an array containing objects with common group properties into a new array. Each group should have a unique color array.

To achieve this using JavaScript:

  1. Create a Mapping of Group Names to Values:
    Create an empty object, group_to_values. Then, traverse through the input array, myArray, using the reduce method.
  • For each object in myArray, check the group property.
  • Store the group property as a key in group_to_values.
  • Create an array at that key if it doesn't exist.
  • Push the color property of the object into the array at the corresponding group key.
var group_to_values = myArray.reduce(function (obj, item) {
    obj[item.group] = obj[item.group] || [];
    obj[item.group].push(item.color);
    return obj;
}, {});
Copy after login
  1. Transform into Desired Format:
    Convert the group_to_values object into the desired array format. Use Object.keys() to get the group names and transform them into objects.
var groups = Object.keys(group_to_values).map(function (key) {
    return {group: key, color: group_to_values[key]};
});
Copy after login

The result, groups, will be an array of objects, each representing a group, with a color array containing all unique colors for that group.

The above is the detailed content of How to Group Array Items by Object Properties in JavaScript?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template