How do I remove an array item in TypeScript?

ArraysTypescriptCollections

Arrays Problem Overview


I have an array that I've created in TypeScript and it has a property that I use as a key. If I have that key, how can I remove an item from it?

Arrays Solutions


Solution 1 - Arrays

Same way as you would in JavaScript.

delete myArray[key];

Note that this sets the element to undefined.

Better to use the Array.prototype.splice function:

const index = myArray.indexOf(key, 0);
if (index > -1) {
   myArray.splice(index, 1);
}

Solution 2 - Arrays

let foo_object; // Itemitem(object here) to remove
this.foo_objects = this.foo_objects.filter(obj => return obj !== foo_object);

Solution 3 - Arrays

With ES6 you can use this code :

removeDocument(doc){
   this.documents.forEach( (item, index) => {
     if(item === doc) this.documents.splice(index,1);
   });
}

Solution 4 - Arrays

It is my solution for that:

onDelete(id: number) {
    this.service.delete(id).then(() => {
        let index = this.documents.findIndex(d => d.id === id); //find index in your array
        this.documents.splice(index, 1);//remove element from array
    });

    event.stopPropagation();
}

Solution 5 - Arrays

You can use the splice method on an array to remove the elements.

for example if you have an array with the name arr use the following:

arr.splice(2, 1);

so here the element with index 2 will be the starting point and the argument 2 will determine how many elements to be deleted.

If you want to delete the last element of the array named arr then do this:

arr.splice(arr.length-1, 1);

This will return arr with the last element deleted.

Example:

var arr = ["orange", "mango", "banana", "sugar", "tea"];
arr.splice(arr.length-1, 1)
console.log(arr); // return ["orange", "mango", "banana", "sugar"]

Solution 6 - Arrays

let departments is an array. You want to remove an item from this array.

departments: string[] = [];

 removeDepartment(name: string): void {
    this.departments = this.departments.filter(item => item != name);
  }

Solution 7 - Arrays

This worked for me.

Your array:

DummyArray: any = [
    { "id": 1, "name": 'A' },
    { "id": 2, "name": 'B' },
    { "id": 3, "name": 'C' },
    { "id": 4, "name": 'D' }
]

Function:

remove() {
    this.DummyArray = this.DummyArray.filter(item => item !== item);
}

Note: This function deletes all the objects form your array. If you want to delete a specific object from array then use this method:

remove(id) {
    this.DummyArray = this.DummyArray.filter(item => item.id !== id);
}

Solution 8 - Arrays

Here's a simple one liner for removing an object by property from an array of objects.

delete this.items[this.items.findIndex(item => item.item_id == item_id)];

or

this.items = this.items.filter(item => item.item_id !== item.item_id);

Solution 9 - Arrays

Use this, if you need to remove a given object from an array and you want to be sure of the following:

  • the list is not reinitialized
  • the array length is properly updated
    const objWithIdToRemove;
    const objIndex = this.objectsArray.findIndex(obj => obj.id === objWithIdToRemove);
    if (objIndex > -1) {
      this.objectsArray.splice(objIndex, 1);
    }

Solution 10 - Arrays

Multiple options in Typescript/Javascript to remove an element from Array. Splice is the best option as

  1. It removes inline without creating a new object
  2. It properly updates the length of the array (wont leave blank null element)

Below is an example of removing an object based on some field in a object array using Splice function

const persons = [
 {
   firstName :'John',
   lastName :'Michel'
  },
  {
   firstName :'William',
   lastName :'Scott'
  },  
  {
   firstName :'Amanda',
   lastName :'Tailor'
  }
]

console.log('Before Deleting :'+JSON.stringify(persons));
console.log('Deleting William:');
persons.splice(persons.findIndex(item => item.firstName === 'William'),1);
console.log('After Deleting William'+JSON.stringify(persons));

Solution 11 - Arrays

Answer using TypeScript spread operator (...)

// Your key
const key = 'two';

// Your array
const arr = [
    'one',
    'two',
    'three'
];

// Get either the index or -1
const index = arr.indexOf(key); // returns 0


// Despite a real index, or -1, use spread operator and Array.prototype.slice()    
const newArray = (index > -1) ? [
    ...arr.slice(0, index),
    ...arr.slice(index + 1)
] : arr;

Solution 12 - Arrays

One more solution using Typescript:

let updatedArray = [];
for (let el of this.oldArray) {
    if (el !== elementToRemove) {
        updated.push(el);
    }
}
this.oldArray = updated;

Solution 13 - Arrays

let a: number[] = [];

a.push(1);
a.push(2);
a.push(3);

let index: number = a.findIndex(a => a === 1);

if (index != -1) {
	a.splice(index, 1);
}

console.log(a);

Solution 14 - Arrays

Just wanted to add extension method for an array.

interface Array<T> {
      remove(element: T): Array<T>;
    }
    
    Array.prototype.remove = function (element) {
      const index = this.indexOf(element, 0);
      if (index > -1) {
        return this.splice(index, 1);
      }
      return this;
    };

Solution 15 - Arrays

You can try to get index or position of list or array first, then use for loop to assign current array to a temp list, filter out unwanted item and store wanted item back to original array

removeItem(index) {
    var tempList = this.uploadFile;
    this.uploadFile = [];

    for (var j = 0; j < tempList.length; j++) {
      if (j != index)
        this.uploadFile.push(tempList[j]);
    }
  }

Solution 16 - Arrays

We can implement the logic using filter and includes

const checkAlpha2Code = ['BD', 'NZ', 'IN']

let countryAlpha2Code = ['US', 'CA', 'BD', 'NZ', 'AF' , 'AR' , 'BR']


/**
 * Returns the modified array countryAlpha2Code 
 * after removing elements which matches with the checkAlpha2Code
 */
countryAlpha2Code = countryAlpha2Code.filter(alpha2code => {
    return !checkAlpha2Code.includes(alpha2code);
});
console.log(countryAlpha2Code)
// Output: [ 'US', 'CA', 'AF', 'AR', 'BR' ]


// Resetting the values again
countryAlpha2Code = ['US', 'CA', 'BD', 'NZ', 'AF' , 'AR' , 'BR']


/**
 * Returns the modified array countryAlpha2Code 
 * which only matches elements with the checkAlpha2Code
 */
countryAlpha2Code = countryAlpha2Code.filter(alpha2code => {
    return checkAlpha2Code.includes(alpha2code);
});

console.log(countryAlpha2Code)
// Output: [ 'BD', 'NZ' ]

Solution 17 - Arrays

I see many complaints that remove method is not in-built. Consider using Set instead of array - it has add and delete methods in-built.

Solution 18 - Arrays

Similar to Abdus Salam Azad answer , but passing array as parameter from //https://love2dev.com/blog/javascript-remove-from-array/

function arrayRemove(arr:[], value:any) { 
    
    return arr.filter(function(ele){ 
        return ele != value; 
    });
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTim AlmondView Question on Stackoverflow
Solution 1 - ArraysblorkfishView Answer on Stackoverflow
Solution 2 - ArraysMalik ShahzadView Answer on Stackoverflow
Solution 3 - ArraysIdakView Answer on Stackoverflow
Solution 4 - ArraysButsatyView Answer on Stackoverflow
Solution 5 - Arraysakash venugopalView Answer on Stackoverflow
Solution 6 - ArraysAbdus Salam AzadView Answer on Stackoverflow
Solution 7 - ArraysAmartya DeshmukhView Answer on Stackoverflow
Solution 8 - ArraysJamie ArmourView Answer on Stackoverflow
Solution 9 - ArraysRadu LinuView Answer on Stackoverflow
Solution 10 - ArraysVenkatesh MuniyandiView Answer on Stackoverflow
Solution 11 - ArraysJoshua Michael CalafellView Answer on Stackoverflow
Solution 12 - ArraysSh. PavelView Answer on Stackoverflow
Solution 13 - ArraysAlessandroView Answer on Stackoverflow
Solution 14 - ArrayssupernerdView Answer on Stackoverflow
Solution 15 - ArraysYisi TanView Answer on Stackoverflow
Solution 16 - ArraysSayef ReyadhView Answer on Stackoverflow
Solution 17 - ArraysBracketsView Answer on Stackoverflow
Solution 18 - ArraysMichael FreidgeimView Answer on Stackoverflow