Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array of objects whose any properties contains a value

I'm wondering what is the cleanest way, better way to filter an array of objects depending on a string keyword. The search has to be made in any properties of the object.

When I type lea I want to go trough all the objects and all their properties to return the objects that contain lea

When I type italy I want to go trough all the objects and all their properties to return the objects that contain italy.

I know there are lot of solutions but so far I just saw some for which you need to specify the property you want to match.

ES6 and lodash are welcome!

  const arrayOfObject = [{       name: 'Paul',       country: 'Canada',     }, {       name: 'Lea',       country: 'Italy',     }, {       name: 'John',       country: 'Italy',     }, ];      filterByValue(arrayOfObject, 'lea')   // => [{name: 'Lea',country: 'Italy'}]     filterByValue(arrayOfObject, 'ita')   // => [{name: 'Lea',country: 'Italy'}, {name: 'John',country: 'Italy'}]
like image 854
Léo Coco Avatar asked Jun 01 '17 16:06

Léo Coco


People also ask

Which function filters the value of an array?

The JavaScript filter array function is used to filter an array based on specified criteria. After filtering it returns an array with the values that pass the filter. The JavaScript filter function iterates over the existing values in an array and returns the values that pass.


2 Answers

You could filter it and search just for one occurence of the search string.

Methods used:

  • Array#filter, just for filtering an array with conditions,

  • Object.keys for getting all property names of the object,

  • Array#some for iterating the keys and exit loop if found,

  • String#toLowerCase for getting comparable values,

  • String#includes for checking two string, if one contains the other.

function filterByValue(array, string) {      return array.filter(o =>          Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));  }    const arrayOfObject = [{ name: 'Paul', country: 'Canada', }, { name: 'Lea', country: 'Italy', }, { name: 'John', country: 'Italy' }];    console.log(filterByValue(arrayOfObject, 'lea')); // [{name: 'Lea', country: 'Italy'}]  console.log(filterByValue(arrayOfObject, 'ita')); // [{name: 'Lea', country: 'Italy'}, {name: 'John', country: 'Italy'}]
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 194
Nina Scholz Avatar answered Sep 22 '22 06:09

Nina Scholz


Well when we already know that its not going to be a search on an object with methods, we can do the following for saving bit on time complexity :

function filterByValue(array, value) {   return array.filter((data) =>  JSON.stringify(data).toLowerCase().indexOf(value.toLowerCase()) !== -1); } 
like image 22
binariedMe Avatar answered Sep 20 '22 06:09

binariedMe