Home > Web Front-end > JS Tutorial > How to Group Array Items into Objects in JavaScript?

How to Group Array Items into Objects in JavaScript?

Patricia Arquette
Release: 2024-12-16 05:43:16
Original
633 people have browsed it

How to Group Array Items into Objects in JavaScript?

Grouping Array Items into Objects

You're tasked with transforming an array of objects into a new array with grouped objects, where the values for each group are combined into an array. Here's how you can approach this problem:

var myArray = [
  {group: "one", color: "red"},
  {group: "two", color: "blue"},
  {group: "one", color: "green"},
  {group: "one", color: "black"}
];
Copy after login
// Create a mapping of group names to arrays of values
var group_to_values = myArray.reduce(function (obj, item) {
  obj[item.group] = obj[item.group] || [];
  obj[item.group].push(item.color);
  return obj;
}, {});
Copy after login
// Convert the mapping to an array of grouped objects
var groups = Object.keys(group_to_values).map(function (key) {
  return {group: key, color: group_to_values[key]};
});
Copy after login

The resulting groups array will be:

[
  {group: "one", color: ["red", "green", "black"]},
  {group: "two", color: ["blue"]}
]
Copy after login

This approach utilizes the reduce and map array methods to efficiently group and transform the data.

The above is the detailed content of How to Group Array Items into Objects in JavaScript?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template