Home >Web Front-end >JS Tutorial >How to Group Array Items by a Common Property in JavaScript?

How to Group Array Items by a Common Property in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-18 19:50:11988browse

How to Group Array Items by a Common Property in JavaScript?

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:

  1. Create a mapping object that maps each "group" property value to an empty array.
  2. Iterate over each item in the original array and:
    a. Retrieve the "group" property value.
    b. If the mapping object contains a key for that "group" property value, push the "color" property value into the associated array. Otherwise, add a new key to the mapping object with a value of an empty array and push the "color" property value into that array.
  3. Finally, transform the mapping object into the desired format, where keys are the "group" property values and values are objects with "group" and "color" properties.

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!

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