[javascript] Group array items using object

My array is something like this:

myArray = [
  {group: "one", color: "red"},
  {group: "two", color: "blue"},
  {group: "one", color: "green"},
  {group: "one", color: "black"}

I want to convert this into:

myArray = [
  {group: "one", color: ["red", "green", "black"]}
  {group: "two", color: ["blue"]}

So, basically, group by group.

I'm trying:

for (i in myArray){
  var group = myArray[i].group;
  //myArray.push(group, {???})

I just don't know how to handle the grouping of similar group values.

This question is related to javascript

The answer is

Start by creating a mapping of group names to values. Then transform into your desired format.

var myArray = [_x000D_
    {group: "one", color: "red"},_x000D_
    {group: "two", color: "blue"},_x000D_
    {group: "one", color: "green"},_x000D_
    {group: "one", color: "black"}_x000D_
var group_to_values = myArray.reduce(function (obj, item) {_x000D_
    obj[item.group] = obj[item.group] || [];_x000D_
    return obj;_x000D_
}, {});_x000D_
var groups = Object.keys(group_to_values).map(function (key) {_x000D_
    return {group: key, color: group_to_values[key]};_x000D_
var pre = document.createElement("pre");_x000D_
pre.innerHTML = "groups:\n\n" + JSON.stringify(groups, null, 4);_x000D_

Using Array instance methods such as reduce and map gives you powerful higher-level constructs that can save you a lot of the pain of looping manually.

Similar questions with javascript tag: