Search code examples
javascriptlodash

Lodash: Combine array object


I want to combine the array with same id for example

var student = [{
   'id': 'xx001',
   'code': 'taller',
   'item': 2,
   'date': '2019-01-01'
},{
   'id': 'xx001',
   'code': 'taller',
   'item': 5,
   'date': '2019-01-01'
},{
   'id': 'xx001',
   'code': 'taller',
   'item': 5,
   'date': '2019-03-24'
},{
   'id': 'xx002',
   'code': 'small',
   'item': 2,
   'date': '2019-01-01'
}]

and the output should be.

enter image description here

and when it combine the same id it will added the item and if the date is not the same it should seperate.


Solution

  • Don't really need lodash, but since it's asked for you can loop using _.forEach and then check if we already have the item using _.find()

    Snippet I have also included a non-lodash version:

    var students = [{
      'id': 'xx001',
      'code': 'taller',
      'item': 2
    }, {
      'id': 'xx001',
      'code': 'taller',
      'item': 5
    }, {
      'id': 'xx002',
      'code': 'small',
      'item': 2
    }];
    
    const output = [];
    _.each(students, x => {
      const existing = _.find(output, {
        id: x.id
      });
    
      if (existing) {
        existing.item += x.item;
      } else {
        output.push(x);
      }
    });
    
    console.info(output);
    
    const students2 = [{
      'id': 'xx001',
      'code': 'taller',
      'item': 2
    }, {
      'id': 'xx001',
      'code': 'taller',
      'item': 5
    }, {
      'id': 'xx002',
      'code': 'small',
      'item': 2
    }];
    
    const output2 = [];
    students2.forEach(x => {
      const existing = output2.find(y => y.id === x.id);
    
      if (existing) {
        existing.item += x.item;
      } else {
        output2.push(x);
      }
    });
    
    console.log(output2);
    
    
    var students3 = [{
       'id': 'xx001',
       'code': 'taller',
       'item': 2,
       'date': '2019-01-01'
    },{
       'id': 'xx001',
       'code': 'taller',
       'item': 5,
       'date': '2019-01-01'
    },{
       'id': 'xx001',
       'code': 'taller',
       'item': 5,
       'date': '2019-03-24'
    },{
       'id': 'xx002',
       'code': 'small',
       'item': 2,
       'date': '2019-01-01'
    }]
    
    const output3 = [];
    students3.forEach(x => {
      const existing = output3.find(y => y.id === x.id && y.date === x.date);
    
      if (existing) {
        existing.item += x.item;
      } else {
        output3.push(x);
      }
    });
    
    console.log(output3);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.min.js"></script>