Kivo
Kivo

Reputation: 435

Typescript filter by multiple values

I have an array and i want to filter it based on multiple values :

let books= [{ bookId : 1},{ bookId : 3},{ bookId : 4},{ bookId : 7},{ bookId : 10}];
let searchValues= [1,7];
let newArray = [];

i can use the spread operator like below :

searchValues.map(book=> {
  newArray.push(...books.filter(f => f.bookId== book.id));
});

but there a way to filter the array using a one liner like this or something similar ? :

newArray = books.filter(f => f.bookId in searchValues);

Thanks.

Upvotes: 1

Views: 1436

Answers (1)

hgb123
hgb123

Reputation: 14881

Use .includes

newArray = books.filter(f => values.includes(f.bookId))

let books = [
  { bookId: 1 },
  { bookId: 3 },
  { bookId: 4 },
  { bookId: 7 },
  { bookId: 10 },
]
let searchValues = [1, 7]
let newArray = []

newArray = books.filter((f) => searchValues.includes(f.bookId))

console.log(newArray)

Upvotes: 4

Related Questions