Problem:
You have an array of objects where each object has a "group" property. You want to transform this array into a new array where similar "group" property values are grouped together.
Desired Output:
myArray = [ {group: "one", color: ["red", "green", "black"]}, {group: "two", color: ["blue"]} ]
Solution:
var group_to_values = {};
myArray.forEach(function (item) { group_to_values[item.group] = group_to_values[item.group] || []; });
var groups = []; for (var key in group_to_values) { groups.push({group: key, color: group_to_values[key]}) }
The above is the detailed content of How Can I Group Objects in an Array Based on a Common Property?. For more information, please follow other related articles on the PHP Chinese website!