Home >Web Front-end >JS Tutorial >How Can I Group Objects in an Array Based on a Common Property?

How Can I Group Objects in an Array Based on a Common Property?

DDD
DDDOriginal
2024-12-23 00:35:26939browse

How Can I Group Objects in an Array Based on a Common Property?

Group Objects by a Common Property

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:

  1. Create a mapping of group names to empty arrays:
var group_to_values = {};
  1. Iterate over the input array:
myArray.forEach(function (item) {
    group_to_values[item.group] = group_to_values[item.group] || [];
});
  1. For each key in the mapping, create an object with the group name and an array of values:
var groups = [];
for (var key in group_to_values) {
    groups.push({group: key, color: group_to_values[key]})
}
  1. The resulting groups array will be grouped by the "group" property.

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!

Statement:
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