2

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.

  • Name: inputbox
  • Team name: dopdownlist (to select team name)
  • Team color: dropdownlist (to select team color)
  • Skills: checkboxes

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.

1
  • What have you tried? Please provide code snippet or explain attempts that failed Commented Mar 17, 2019 at 12:42

1 Answer 1

2

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"]))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.