Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing Items from an Array in Typescript Using .filter() – Immutable Pattern

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading