Search code examples
lodash

Lodash differenceBy alternative


I am trying to find a way to differentiate between 2 object literals by a property from each. I can get this working by using 2 ._forEach()

_.forEach(forms, form => {
    _.forEach(this.sections, section => {
        if(form.section === section.name){
          section.inProgress = true;
        }
    });
});

However this does not seem ideal. I have tried with the _.differenceBy

_.differenceBy(forms, this.sections, 'x');

But I cant differentiate by the property name as the "name" that i want to check by is name in one of the arrays and section in the other.

I want to use something like

_.differenceBy(forms, this.sections, 'section' === 'name');

It there something in lodash for this?


Solution

  • You can use _.differenceWith() with a comparator that refers to a specified object property in each array:

    var forms = [{ 'name': 'somethingA' }, { 'name': 'somethingB' }];
    var sections = [{ section: 'somethingB' }];
    
    var result = _.differenceWith(forms, sections, function(arrValue, othValue) {
      return arrValue.name === othValue.section;
    });
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>