lodash _.find all matches

JavascriptLodash

Javascript Problem Overview


I have simple function to return me object which meets my criteria.

Code looks like:

    var res = _.find($state.get(), function(i) {
        var match = i.name.match(re);
        return match &&
            (!i.restrict || i.restrict($rootScope.user));
    });

How can I find all results (not just first) which meets this criteria but all results.

Thanks for any advise.

Javascript Solutions


Solution 1 - Javascript

Just use _.filter - it returns all matched items.

_.filter > Iterates over elements of collection, returning an array of all elements predicate returns truthy for. The predicate is invoked with three arguments: (value, index|key, collection).

Solution 2 - Javascript

You can use _.filter, passing in all of your requirements like so:

var res = _.filter($state.get(), function(i) {
        var match = i.name.match(re);
        return match &&
            (!i.restrict || i.restrict($rootScope.user));
    });

Link to documentation

Solution 3 - Javascript

Without lodash using ES6, FYI:

Basic example (gets people whose age is less than 30):

const peopleYoungerThan30 = personArray.filter(person => person.age < 30)

Example using your code:

$state.get().filter(i => {
    var match = i.name.match(re);
    return match &&
            (!i.restrict || i.restrict($rootScope.user));
})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnduritView Question on Stackoverflow
Solution 1 - JavascriptstasovlasView Answer on Stackoverflow
Solution 2 - JavascriptGerard SimpsonView Answer on Stackoverflow
Solution 3 - JavascriptABCD.caView Answer on Stackoverflow