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:
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]}; });
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!