Javascript array search filter

I have the scenario, with provided example JSON data:

[{
   "name": "Joe",
   "age": "28",
   "hobby": ["Reading", "Chilling", "Cycling"]
},
{
   "name": "Beck",
   "age": "25",
   "hobby": ["Drinking", "Cycling"]
},
{
   "name": "Candace",
   "age": "24",
   "hobby": ["Reading", "Singing"]
}]

Let's say the array above are shown in some list in web page.

I have 2 (two) search dropdown with multiple selection to search name and age.

  • For name, let's say it shows all distinct hobbies (Reading, Chilling, Cycling, Drinking, Singing).
  • For age, let's say it have 2 options for age range: 23-26 and > 27.

For searching hobby, my code is (in ReactJS):

filteredPersons = this.state.personList.filter( person =>{
  return person.hobby.some(v=> filterHobby.indexOf(v) !== -1)
});

which is:

  • personList is list of array from JSON above;
  • filterHobby is list of array from multiple select, ex: if filterHobby = ["Reading","Singing"], it will show Joe and Candace.

The question is, how can I search for age with multiple selection?

Expected result:

  • Choose 23-26 only will show Beck and Candace
  • Choose >27 only will show Joe
  • Choose both will show Beck, Candace and Joe

Thank you for any answer.


You could take an object with all filters and another for keeping function for getting the ages of the objects.

var data = [{ name: "Joe", age: "28", hobby: ["Reading", "Chilling", "Cycling"] }, { name: "Beck", age: "25", hobby: ["Drinking", "Cycling"] }, { name: "Candace", age: "24", hobby: ["Reading", "Singing"] }],
    functions = {
        '23-26': ({ age }) => age >= 23 && age <= 26,
        '>27': ({ age }) => age > 27
    },
    filters = {
        hobby:  ["Reading", "Cycling"],                
        age: ['23-26']
    },
    result = data.filter(o =>  
        filters.hobby.some(v => o.hobby.includes(v)) &&
        filters.age.some(fn => functions[fn](o))
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to create JavaScript list filter and search, JavaScript Array filter() method in detail filter(callback, contextObject); The filter() method creates a new array with all the elements that pass the test implemented by the callback() function. Internally, the filter() method iterates over each element of the array and pass each element to the callback function. The filter() method creates an array filled with all array elements that pass a test (provided as a function). Note: filter() does not execute the function for array elements without values. Note: filter() does not change the original array.


You need use filter function for filtering an array.

We have an array with persons:

const persons = [
    {
       "name": "Joe",
       "age": "28",
       "hobby": ["Reading", "Chilling", "Cycling"]
    },
    {
       "name": "Beck",
       "age": "25",
       "hobby": ["Drinking", "Cycling"]
    },
    {
       "name": "Candace",
       "age": "24",
       "hobby": ["Reading", "Singing"]
    }
]

And then we will filter that array:

persons.filter((person) => {
    return person.age > 27;
})

This code returns us Joe's info:

[
  {
    "name": "Joe",
    "age": "28",
    "hobby": ["Reading", "Chilling", "Cycling"]
  }
]

JavaScript Array Filter: Filtering Array Elements Based on a Test , is a Community author on DigitalOcean. Still looking for an answer? Ask a question Search for more help. In JavaScript, filter() is an Array method that is used to return a new array with only those elements that meet a specific criteria. Because the filter() method is a method of the Array object, it must be invoked through a particular instance of the Array class.


For search person by its age, you can make an array of a selected age like this.

let ages = ['23','24','25'];

code like this

persons.filter(item=> {return ages.indexOf(item.age)!== -1 })

this return person array which are matches in ages array

output:

[
  { name: 'Beck', age: '25', hobby: [ 'Drinking', 'Cycling' ] },
  { name: 'Candace', age: '24', hobby: [ 'Reading', 'Singing' ] }
]

filter() Array Method in JavaScript, JavaScript Array filter() Method The filter() method creates an array filled with all array elements that pass a test (provided as a function). Note: filter() does not execute the function for array elements without values. Note: filter() does not change the original array. Below examples illustrate the arr.filter() method in JavaScript: Example 1: In this example, the method filter() creates a new array consisting of only those elements that satisfy the condition checked by isPositive() function.


ageFilters = ['23-26','>27']
selectedFilter = '23-26';

filteredPersons = this.state.persons.filter(({age}) => {
 const _age = parseInt(age);
 if(selectedFilter === '23-26') {             // "23-26"
  return (_age>=23) && (_age<=26);
 } else if(selectedFilter === '>27') {                          // "27"
  return (_age>27);
 } else {
  return true;
 }
})

JavaScript Array filter() Method, If you are working on browsers supporting JavaScript 1.6, Array.filter is your choice. Your problem can be solved by the following� The search will start at the specified position, or at the beginning if no start position is specified, and end the search at the end of the array. Returns -1 if the item is not found. If the item is present more than once, the indexOf method returns the position of the first occurence.


You may create additional function ageComparer for convenience

const ageComparer = (ageRange, age) => (ageRange === '23-26' ? (age >= 23 && age <= 26) : age >=27)

And then utilize it during filtering

// ageFilter will be taken from drom down
const ageFilter = ['23-26'];

person.filter(p => p.hobby.some(v=> filterHobby.indexOf(v) !== -1) && ageFilter.some(a => ageComparer(a, +p.age)))

Array filtering by search query, Return value: This method returns a new array consisting of only those elements that satisfied the condition of the arg_function. Below examples� JavaScript Filter Array() Method to Filter Complex Arrays in an Easy Way JavaScript Filter using Fat Arrow Function in ECMAScript 6 All thanks to the entry of arrow functions in ECMAScript, it has become even simpler to use array filter JavaScript .


JavaScript Array filter() Method, To start with, this technique assumes that the data you're filtering over is in the form of an array of objects. From there� For all these use cases, JavaScript's Array.prototype methods have you covered. In this article, we will discuss four methods we can use to search for an item in an array. These methods are: Filter; Find; Includes; IndexOf; Let's discuss each of them. Array.filter() We can use the Array.filter() method to find elements in an array that meet a


Quick and Simple Search Filter Using Vanilla JavaScript ― Scotch.io, Javascript array filter() is an inbuilt function that creates the new array element of an array and returns the values which coerce the value true. Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function. In this article, you will learn why and how to use each one. Here is a fun summary by Steven Luscher: > Map/filter/reduce in a tweet: map([🌽, 🐮, 🐔], cook


4 Methods to Search Through Arrays in JavaScript ← Alligator.io,