natario
natario

Reputation: 25194

Deep array selection with lodash

I have barely used lodash and I’m trying to use it now for a simple task.

I have a working solution, but it looks complex and I wonder if there’s a easy shorthand to the task using the library utilities.

items is an array of objects like the following:

{
    id: ‘string’,
    val_1: ‘string’,
    val_2: ‘string’,
    components: array of: {
        val_3: ‘string’,
        val_4: ‘string’,
        types: array of strings
    }
}

I want to select an object whose components array holds valid types. Valid types are defined by me in an array of about 10 strings. This is my solution:

var validTypes = [‘type1’,’type3’,’type5’];
var desired = _.find(items, (item) => {
    var allowed = true;
    _.forEach(item.components, (component) => {
        // Remove valid types. What's left should be empty.
        _.pullAll(component.types, validTypes);
        allowed = allowed && _.isEmpty(component.types);
    })
    return allowed;
});

As said, I wonder how this can be improved, I feel like I’m not using lodash correctly.

Upvotes: 0

Views: 361

Answers (1)

Meir
Meir

Reputation: 14375

First of all, _.pullAll mutate your objects and should not be used.

You can use instead _.every and _.some, this will stop the loop once it is found an unacceptable value.

var validTypes = [‘type1’,’type3’,’type5’];
var desired = _.find(items, (item) => {
    return _.every(item.components, (component) => { // all components must be valid
        return _.isEmpty(_.difference(component.types, validTypes)); // there shouldn't be any types that are not in the valid
    }
}

Upvotes: 2

Related Questions