Grouping Array Items Using an Object
When dealing with arrays containing objects, it can be useful to group items based on a common property. This can be achieved by creating a mapping of group names to associated values.
Suppose you have an array like the following:
myArray = [ {group: "one", color: "red"}, {group: "two", color: "blue"}, {group: "one", color: "green"}, {group: "one", color: "black"} ]
You wish to convert it into a new array where items are grouped by the "group" property:
myArray = [ {group: "one", color: ["red", "green", "black"]}, {group: "two", color: ["blue"]} ]
To achieve this, you can use the following steps:
Here is an example 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]}; });
Upon execution, this code will produce the desired grouped array:
groups: { "one": [ "red", "green", "black" ], "two": [ "blue" ] }
The above is the detailed content of How to Group Array Items by a Common Property in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!