John Moore
John Moore

Reputation: 7129

Find matching elements in array and do something for each match

I'm a little overwhelmed by all the functions available to me in Lodash, so I hope someone can point me to the one I'm sure exists which will do the following for me. I want to be able to pass an array and a search condition, and have it loop through all the matched items, allowing me to run a function for each. What I have at the moment is something akin to this:

_.each(myArray, (item) => {
    if (item.field=="whatever") {
      console.log("Matched by "+item.name);
    }
});

This works fine, of course. It's just that I'm sure Lodash has a way for me to move the item.field=="whatever" into the function arguments somehow, and I'd prefer to go with the more idiomatic Lodash way if I can.

Upvotes: 1

Views: 5235

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240878

It's just that I'm sure Lodash has a way for me to move the item.field == "whatever" into the function arguments somehow

If you want to find all the matching items in an array based on the arguments you pass in, then you could use the _.filter method, which can use the _.matches shorthand internally:

_.filter(myArray, { field: 'whatever' });

However, you would still need to loop over the items if you want to do something for each match:

_.each(_.filter(myArray, { field: 'whatever' }), item => {
  console.log("Matched by " + item.name);
});

Alternatively, if you want a different way of writing this, you can wrap the filtered items with the lodash object wrapper, _(), which essentially enables chaining, thereby allowing you to chain the _.each() method:

_(_.filter(myArray, { field: 'whatever' })).each(item => {
  console.log("Matched by " + item.name);
});

Or a more readable version:

var matchedItems = _.filter(myArray, { field: 'whatever' });
_(matchedItems).each(item => {
  console.log("Matched by " + item.name);
});

Personally, I would probably just keep what you originally wrote since it's short, readable and easy to maintain.

Upvotes: 2

Related Questions