Malik Awan
Malik Awan

Reputation: 463

JavaScript array filtering based on any combination of properties

I have array like this.

[{
  id: 1,
  name: 'Stephen',
  Team: {
    name: 'Lion',
    color: 'blue'
  },
  skills: ['allrounder', 'middleorder']
}, {
  id: 2,
  name: 'Daniel',
  Team: {
    name: 'Panther',
    color: 'green'
  },
  skills: ['batsman', 'opener']
}, {
  id: 3,
  name: 'Mark',
  Team: {
    name: 'Lion',
    color: 'blue'
  },
  skills: ['bowler', 'fielder']
}]

I am providing search facility on every field.

User can provide only Name field and click on Search , or can use multiple options like only skills or combination of any of input. What is best way to filter an array based on these conditions. e.g.

myArr.filter(item => item.Name.toLowerCase().startsWith(searchData.name.toLowerCase())
                      && / || item.skills.include(searchData.skillsArr)  

Expected output is based on any single or combination of input provided.

Upvotes: 2

Views: 920

Answers (1)

adiga
adiga

Reputation: 35222

You could write a function using filter like this:

  • Check if there is value in name parameter. If yes, check if the name property of the array object includes the name
  • If not, check for teamName and color parameter in a similar way
  • Then check for an array of selected skills. Check if some of the skills are included in the object's skills array property

const input=[{id:1,name:'Stephen',Team:{name:'Lion',color:'blue'},skills:['allrounder','middleorder']},{id:2,name:'Daniel',Team:{name:'Panther',color:'green'},skills:['batsman','opener']},{id:3,name:'Mark',Team:{name:'Lion',color:'blue'},skills:['bowler','fielder']}]

function filter(array, name, teamName, color, skills) {
  return array.filter(a =>
    (!name || a.name.toLowerCase().includes(name.toLowerCase())) &&
    (!teamName || a.Team.name.toLowerCase().includes(teamName.toLowerCase())) &&
    (!color || a.Team.color.toLowerCase().includes(color.toLowerCase())) &&
    (!skills || skills.length === 0 || skills.some(s => a.skills.includes(s)))
  )
}

console.log(filter(input, "Mark"))
console.log(filter(input, null, "Panther"))
console.log(filter(input, null, null, "blue", ["bowler"]))

Upvotes: 2

Related Questions