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
Release: 2024-12-23 00:35:26
Original
911 people have browsed it

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"]}
]
Copy after login

Solution:

  1. Create a mapping of group names to empty arrays:
var group_to_values = {};
Copy after login
  1. Iterate over the input array:
myArray.forEach(function (item) {
    group_to_values[item.group] = group_to_values[item.group] || [];
});
Copy after login
  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]})
}
Copy after login
  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!

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