Search code examples
javascriptlodash

merging arrays using lodash


I have this set of an array of objects:

let x = [{
    CategoryName: 'abc',
    Items: ['3A']
  },
  {
    CategoryName: 'xyz',
    Items: ['5Z']
  },
  {
    CategoryName: 'abc',
    Items: ['6B']
  },
  {
    CategoryName: 'abc',
    Items: ['9C']
  },
  {
    CategoryName: 'xyz',
    Items: ['1X']
  }
];

what I want is:

[
    {CategoryName:'abc',Items['3A','6B','9C']},
    {CategoryName:'xyz',Items['1X','5Z']}
]

How I can I achieve this using lodash?


Solution

  • You can group it by CategoryName and flatMap that result by Items. That's it!

    _(x).groupBy('CategoryName').map((v, k)=> ({CategoryName: k, Items: _.flatMap(v, 'Items')})).value()
    

    Working demo:

    let x = [{"CategoryName":"abc","Items":["3A"]},{"CategoryName":"xyz","Items":["5Z"]},{"CategoryName":"abc","Items":["6B"]},{"CategoryName":"abc","Items":["9C"]},{"CategoryName":"xyz","Items":["1X"]}],
        res;
        
    res = _(x).groupBy('CategoryName').map((v, k)=> ({CategoryName: k, Items: _.flatMap(v, 'Items')})).value();
    
    console.log(res);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>