I have an interface with some fields like that:
interface Item {
    id: number;
    name: string;
}
And I want to implement a method removeItemsWithName(items: Item[], name: string) which removes all items from the given array, which have the given name:
const myItems: Item[] = [
    { id: 1, name: 'foo' },
    { id: 2, name: 'foo' },
    { id: 3, name: 'bar' }
];
removeItemsWithName(myItems, 'foo');
console.log(myItems);
The result should be:
[{id: 3, name: 'bar'}]
Is there a method array.removeIf() (like Collection.removeIf() in Java 8) available in typescript/javascript, so that my method could look like something similar to this:
function removeItemsWithName(items: Item[], name: string): void {
    items.removeIf(i => i.name === name);
}
I already found the question Remove array element based on object property, but I need to modify the original array in place instead of creating a new one (like array.filter() does). I also want to remove all items matching the condition, not just the first one.
The standard solution would be filter, but this returns a new array:
function removeItemsWithName(items: Item[], name: string): Item[] {
  return items.filter(i => i.name !== name);
}
However, if you really need to modify the array in place, you'd have to use something like this:
function removeItemsWithName(items: Item[], name: string): void {
  let j = 0;
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (item.name !== name) {
        items[j] = item;
        j++;
    }
  }
  items.length = j;
}
Or with splice:
function removeItemsWithName(items: Item[], name: string): void {
  for (let i = 0; i < items.length; i++) {
    if (items[i].name === name) {
      items.splice(i--, 1);
    }
  }
}
Or you can use a library like lodash which has a convenient remove method:
import _remove from 'lodash/remove';
function removeItemsWithName(items: Item[], name: string): void {
  _remove(items, x => x.name === name);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With