Home > Software engineering >  Lodash how to group array of objects by array of values?
Lodash how to group array of objects by array of values?

Time:09-06

I want to group an array of objects based on a property which has an array of values,and i want to return a group for each individual value,not only for the whole array.

For example :

let crew = [
  {
    name:"john",
    job :["electrician","carpenter"]
  },
  {
    name: "bill",
    job: ["electrician"]
  },
  {
    name: "mark",
    job: [ "carpenter"]
  }
]

let groupedCrew = _.groupBy(crew,"job")


console.log(groupedCrew)

/*
  carpenter:
    [
      {
        job:
          [
            carpenter
          ],
        name:
          "mark"
      }
    ],
  electrician:
    [
      {
        job:
          [
            "electrician"
          ],
        name:
          "bill"
      }
    ],
  electrician, carpenter:
    [
      {
        job:
          [
            "electrician",
            "carpenter"
          ],
        name:
          "john"
      }
    ]
}
*/

In this example i want "john" to also appear in "electrician" group. Any ideas ?

CodePudding user response:

Once again let's group something using reduce Here's the basic structure (plus the solution)

let crew = [{
    name: "john",
    job: ["electrician", "carpenter"]
  },
  {
    name: "bill",
    job: ["electrician"]
  },
  {
    name: "mark",
    job: ["carpenter"]
  }
];

var obj = crew.reduce(function(agg, item) {

  // grouping logic below this line
  item.job.forEach(function(job) {
    agg[job] = agg[job] || []

    // agg[job].push (item);
    // lets push only name so we can see output
    agg[job].push(item.name)

  })

  // grouping logic above this line

  return agg
}, {})

console.log(obj)

CodePudding user response:

use custom .reduce() function

there is no need for lodash

const crew = [
    {
        name: 'john',
        job: ['electrician', 'carpenter'],
    },
    {
        name: 'bill',
        job: ['electrician'],
    },
    {
        name: 'mark',
        job: ['carpenter'],
    },
];

const groupedCrew = crew.reduce((groupedCrew, person) => {
    person.job.forEach(job => {
        if (!groupedCrew[job]) groupedCrew[job] = [];
        groupedCrew[job].push(person);
    });
    return groupedCrew;
}, {});

console.log(JSON.stringify(groupedCrew, null, 4));

  • Related