Home > front end >  How to filter a list by multiple parameters in JavaScript
How to filter a list by multiple parameters in JavaScript

Time:01-24

I've got a list:

const list = [{
  name: 'Simon',
  age: 18
}, {
  name: 'Simon',
  age: 22
}, {
  name: 'Martha',
  age: 18
}]

and my filter params are:

const filterParams = {
  name: 'Simon',
  age: 18
}

I want to apply my filter params to filter my list, but I can pass one or 2 params.

 {
  name: 'Simon'
}

 OR

 {
  name: 'Simon',
  age: 18
}

My ideia is to iterate through my filterParams and filter those entries in the list.

const filteredList = Object.entries(filterParams).map(([key, value]) => list.filter(l => l[key] === value))

USE CASES

  1. If I pass
{
  name: 'Simon',
  age: 18
}

the expected result is:

const expectedResult = [{
  name: 'Simon',
  age: 18
}]
  1. If I pass
{
  name: 'Simon',
}

the expected result is:

const expectedResult = [{
  name: 'Simon',
  age: 18
}, {
  name: 'Simon',
  age: 22
}]

Somehow I couldn't figure out yet and obviously my filter function is not working. Here's a code snippet.

const filterParams = {
  name: 'Simon',
  age: 18
}

const list = [{
  name: 'Simon',
  age: 18
}, {
  name: 'Simon',
  age: 22
}, {
  name: 'Martha',
  age: 18
}]



const filteredList = Object.entries(filterParams).map(([key, value]) => list.filter(l => l[key] === value))


const expectedResult = [{
  name: 'Simon',
  age: 18
}]

console.log('filteredList', filteredList)

Thanks in advance

CodePudding user response:

You're going thru the filters, and mapping them to each list item. What you need to do is map the list items instead, and compare each item's values to the filters.

const filterParams = {
  name: 'Simon',
  age: 18
}

const list = [{
  name: 'Simon',
  age: 18
}, {
  name: 'Simon',
  age: 22
}, {
  name: 'Martha',
  age: 18
}]

const filteredList = list.filter(item => {
  return Object.keys(filterParams).every(param => {
    return filterParams[param] === item[param];
  });
});

const expectedResult = [{
  name: 'Simon',
  age: 18
}]

console.log('filteredList', filteredList)

  • Related