Reputation: 463
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
Reputation: 35222
You could write a function using filter
like this:
name
parameter. If yes, check if the name
property of the array object includes
the nameteamName
and color
parameter in a similar wayskills
. Check if some
of the skills are included
in the object's skills
array propertyconst 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