Home > Software engineering >  Removing Items from an Array in Typescript Using .filter() - Immutable Pattern
Removing Items from an Array in Typescript Using .filter() - Immutable Pattern

Time:03-10

I am trying to remove item from array Using .filter() - Immutable Pattern

const drinks = ['Cola', 'Lemonade', 'Coffee', 'Water'];
const id = 'Coffee';
const idx = drinks.indexOf(id);
const removedDrink = drinks[idx];
const filteredDrinks = drinks.filter((drink, index) => drink !== idx);

But the problem I have that I have error like this

const idx: number This condition will always return 'true' since the types 'string' and 'number' have no overlap

CodePudding user response:

With .filter's callback, the first argument is the value being iterated over, and the second argument is the index being iterated over. TypeScript is correctly warning you that comparing the idx - a number - to one of the array elements - a string - doesn't make sense.

indexOf is completely superfluous anyway here. Just use

const drinks = ['Cola', 'Lemonade', 'Coffee', 'Water'];
const id = 'Coffee';
const filteredDrinks = drinks.filter(drink => drink !== id);
  • Related