Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter an array of objects by keyword using LoDash?

Let's say I have an array of objects like this:

[{
  away: "Seattle Seahawks",
  home: "Kansas City Chiefs",
},
{
  away: "Houston Texans",
  home: "San Francisco 49ers",
},
{
  away: "Dallas Cowboys",
  home: "Los Angeles Rams",
}]

Requirements:

Search every object and for the keyword 49er and have it return object #2.

Search every object for the keyword cow and have it return object #3.

Search every object for the keyword an and have it return all three objects.

What would be the best way to achieve this in lodash? Thanks!

like image 571
nomad Avatar asked Feb 07 '23 10:02

nomad


2 Answers

My solution with _.flow:

const my_arr = [{
  away: "Seattle Seahawks",
  home: "Kansas City Chiefs",
},
{
  away: "Houston Texans",
  home: "San Francisco 49ers",
},
{
  away: "Dallas Cowboys",
  home: "Los Angeles Rams",
}]

function flowFilter(array, substr) {
    return _.filter(array, _.flow(
    _.identity,
    _.values,
    _.join,
    _.toLower,
    _.partialRight(_.includes, substr)
  ));
}

const one = flowFilter(my_arr, '49er');
const two = flowFilter(my_arr, 'cow');
const three = flowFilter(my_arr, 'an');

console.log('one', one);
console.log('two', two);
console.log('three', three);

https://jsfiddle.net/1321mzjw/

like image 159
Mikhail Shabrikov Avatar answered Feb 08 '23 23:02

Mikhail Shabrikov


No need of lodash library use native JavaScript methods.

var data = [{
  away: "Seattle Seahawks",
  home: "Kansas City Chiefs",
}, {
  away: "Houston Texans",
  home: "San Francisco 49ers",
}, {
  away: "Dallas Cowboys",
  home: "Los Angeles Rams",
}];

console.log(
  // filter the array
  data.filter(function(v) {
    // get all keys of the object
    return Object.keys(v)
    // iterate and check for any object property value cotains the string
    .some(function(k) {
      // convert to lowercase(to make it case insensitive) and check match
      return v[k].toLowerCase().indexOf('49ers') > -1;
    })
  })
);

console.log(
  data.filter(function(v) {
    return Object.keys(v).some(function(k) {
      return v[k].toLowerCase().indexOf('an') > -1;
    })
  })
);
like image 39
Pranav C Balan Avatar answered Feb 09 '23 00:02

Pranav C Balan