0

I have a multi select dropdown in Angular. I want to filter it out based on name.

var users = [{
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    address: 'USA'
  },
  {
    name: 'Tom',
    email: 'tom@mail.com',
    age: 35,
    address: 'England'
  },
  {
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    address: 'England'
  }
];

How will i filter out John and Tom both if i select them in my multi select dropdown. Assuming i am getting this from the multiselect dropdown.

this.selectedItems = 
[
{"id":1,"name":"John"},                             
{"id":2,"name":"Tom"}
];
Rahul Jain
  • 39
  • 5
  • @RahulJain Please share the code you tried, if possible a stackblitz with the issue replicated and screenshots of the expected output for best resolution! – Naren Murali Dec 13 '22 at 07:16

2 Answers2

1

You can approach this by using filter method.

let selectedUserArray = ["John","Tom"]; //selected user names from the dropdown.

let finalArr = [];

selectedUserArray.forEach((item)=>{
    var name = users.filter( el=>el.name == item );
    finalArr.push.apply(finalArr,name);
});

console.log(finalArr); // This is the final Array you want to approach
Asna Khan
  • 215
  • 1
  • 8
  • Thank you, this works if i have selected array as just names. Below one works if i have index with them also. – Rahul Jain Dec 13 '22 at 12:15
1
const selectedUserNames = this.selectedItems.map(user => user.name);
const selectedUsers = users.filter(user => selectedUserNames.indexOf(user.name) > -1)
Wyrzutek
  • 605
  • 1
  • 5
  • 13