0

This is array I want to filter

[
    0: {id: 1, name: "Berlin",}
    1: {id: 2, name: "Proffesor",}
    2: {id: 4, name: "Oslo",}
    3: {id: 6, name: "Denver",}
]

This is array for filter

 [6, 16, 2, 10, 24]

This is my pipe

export class ChatPipe implements PipeTransform {

  transform(user: Users[], args: any): any { //for users i use first array and for args I use second
    if (!user || !args) {
      return user;
      
  }
  
  let filteri = user.filter(users => users.id == args);
  
  return filteri;
};

}

I want to filter first array using values from another. Can anyone help me?

1
  • let filteri = user.filter(item => args.includes(item.id)); should do the trick Commented Jun 1, 2021 at 9:50

2 Answers 2

2

change this :

// let filteri = user.filter(users => users.id == args);
// return filteri;
return (user || []).filter((item: any) => (args || []).includes(item.id));

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

Comments

1

Event though you are not telling us your desire output, I guess that you wanna filter the first array with the values of the second one by id.

First of all create your users array to be like an array:

Instead of this:

[
    0: {id: 1, name: "Berlin",}
    1: {id: 2, name: "Proffesor",}
    2: {id: 4, name: "Oslo",}
    3: {id: 6, name: "Denver",}
]

Make it like this:

[
    {id: 1, name: "Berlin"},
    {id: 2, name: "Proffesor"},
    {id: 4, name: "Oslo"},
    {id: 6, name: "Denver"},
]

After that your pipe should be like this:

@Pipe({
    name: 'filterUsersByIds',
    pure: false
})
export class FilterUsersByIdsPipe implements PipeTransform {
    transform(users: user[], filters: number[]): any {
        if (!users || !filters) {
            return users;
        }
        
        return users.filter(user => filters.some(x => user.id === x));
    }
}

PS: Don't forget to declare the pipe in a module before using the pipe in your HTML.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.