730

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?

Marco
  • 1,377
  • 15
  • 18
Tim Almond
  • 12,088
  • 10
  • 40
  • 50

20 Answers20

1048

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);
}
zgue
  • 3,793
  • 9
  • 34
  • 39
blorkfish
  • 21,800
  • 4
  • 33
  • 24
  • 13
    You can add a type to that! `var index: number = myArray.indexOf(key, 0);` – CorayThan Dec 19 '15 at 00:38
  • 31
    @CorayThan Surely it would be implicitly typed as `indexOf` returns a `number`? – Chris Jun 08 '16 at 10:27
  • 8
    @Chris While it's obvious in this simple case, it can help you diagnose bugs faster if you define a type for every variable explicitly. You're using `index` in more than once place already and one of those places (`splice`) wants to see a number or you'll get an error. Currently the compiler can't prevent you making mistakes there. – Jochem Kuijpers Nov 02 '16 at 09:56
  • @JochemKuijpers No, the compiler would create a different variable for all other index variables. So, when you declare your variables with var, let, const, it should be fine. – esskar Mar 31 '17 at 01:12
  • It doesn't set the element to `null`, it removes the property so it will read as `undefined` when accessed. – Yogu Mar 31 '17 at 05:30
  • 51
    @blorkfish it's good to mention that if you have a list of objects, you can use `var index = myArray.findIndex(x => x.prop==key.prop);`. – Francisco Cabral Apr 04 '17 at 14:06
  • `splice` is a _function_ not a keyword. – This company is turning evil. Nov 19 '17 at 19:48
  • 2
    Why `splice` should be better than `delete`? Thanks! – Cirelli94 Feb 05 '18 at 10:37
  • 11
    @Cirelli94 - you're responding to an older thread, but the answer to your question is that deleting an array element does not change its length or re-index the array. Because arrays are objects in JavaScript, `delete myArr[2]` literally deletes _the property_ `2` of `myArr`, which is also different than `myArr[2] = undefined`. The moral of this story is to just use `splice` for this task because it is a safe way to get the desired effect without confusing side effects. – Elianora Feb 28 '18 at 04:23
  • Splice is the right way to go. Filter does not work! – Manto Sep 11 '18 at 23:17
  • suppose i want to remove the all the array data where CategoryID equal to CatID. using spread operator we can clone by using filter method. var l=[...this.ListSubCat.filter(r => r.CategoryID != CatID)]; this.ListSubCat=[]; // Set array as empty this.ListSubCat= l; – Chinthana Gunasekara Jul 08 '19 at 10:46
372
let foo_object; // Itemitem(object here) to remove
this.foo_objects = this.foo_objects.filter(obj => return obj !== foo_object);
Malik Shahzad
  • 6,703
  • 3
  • 37
  • 49
  • 61
    This does not remove anything it simply filters. If the list actually needs to be modified this is not the way. – user573434 Jun 13 '17 at 18:29
  • 11
    @user573434 yes, you are right, as the name indicate. But this is simple approach in case where you want to remove an object on successful delete api call etc. – Malik Shahzad Jun 14 '17 at 09:10
  • 5
    This worked perfectly for me on an array of objects without a unique key property. @user573434 the filter method returns a new array without the filtered object, so the resulting array does have the object removed. – Jason Watmore Jun 25 '17 at 03:22
  • 7
    i think in order to return it as an object you have to do this `this.foo_objects = this.foo_objects.filter(obj => obj !== foo_object)[0];` – Shift 'n Tab Jun 30 '17 at 12:12
  • 1
    This is the simplest solution so far, I like it! I kept wondering about any scenarios where you would want to change the actual array instead of creating a new copy of it, but couldn't think of any. – mikhail-t Feb 26 '18 at 23:24
  • @mik-t I believe that underneath the covers, that's what the javascript engine does anyways because arrays are static sized. – Anshul Jun 29 '18 at 16:33
  • This does not work!! I have used an array to keep track of routerLinks in my Angular App, and when I used the above code, it did not remove the link at all!! Splice works like a charm. – Manto Aug 24 '18 at 03:52
  • 5
    this doesn't modify the original array, it creates a new one – Julio Villane Nov 29 '18 at 13:23
  • 2
    This works. just read the 2nd line carefully. he does a filter with obj != foo_object. and assigns it to the original variable, thus replacing the original array with one minus the filtered foo_object. used it with an array of objects with id `deleteById(id: string) { this.data = this.data.filter(d => d.id !== id); }` Just one word of warning, if Ids are not unique you will remove all with the same `id` – Markus May 05 '19 at 13:17
  • 1
    @Markus. If there are multiple references to the original array, they will not be affected. – Alex May 09 '19 at 17:07
  • This does work, but if you are using the original array for a data store, it will not work as expected since you have to assign the newly return list back to your variable. – André Onuki Jul 27 '20 at 02:08
140

With ES6 you can use this code :

removeDocument(doc){
   this.documents.forEach( (item, index) => {
     if(item === doc) this.documents.splice(index,1);
   });
}
Idak
  • 1,401
  • 1
  • 10
  • 2
43

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();
}
Buzzy
  • 1,783
  • 18
  • 15
  • What's nice about this solution is that it will work even when object equality fails to identify two objects as equal. – Brad Johnson Jun 08 '18 at 20:00
32

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);
  }
Abdus Salam Azad
  • 5,087
  • 46
  • 35
29

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"]
Gius
  • 89
  • 1
  • 1
  • 11
akash venugopal
  • 349
  • 5
  • 7
20

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);
}
Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
19

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);
Jamie Armour
  • 524
  • 5
  • 10
  • 4
    The problem with first solution is that delete removes element, but array size remains the same as before deteling. In second solution we will have a new object, so if we have spme dependency then we are losing it. Splice (which is in the top answer) does not have this effect. – Krystian Nov 13 '19 at 14:20
  • Thanks for pointing that out. I think in my use case I had not discovered that yet. Well observed :) – Jamie Armour Dec 14 '19 at 18:36
12

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);
    }
Radu Linu
  • 1,143
  • 13
  • 29
11

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));
Venkatesh Muniyandi
  • 5,132
  • 2
  • 37
  • 40
  • 1
    I think you have misused the word 'mutate' here because splice definitely mutates the original object – myol Oct 25 '21 at 12:27
7
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);
Alessandro
  • 305
  • 4
  • 12
6

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;
6

One more solution using Typescript:

let updatedArray = [];
for (let el of this.oldArray) {
    if (el !== elementToRemove) {
        updated.push(el);
    }
}
this.oldArray = updated;
Sh. Pavel
  • 1,584
  • 15
  • 28
  • While this does resolve the problem asked, it is expensive to execute because of the creation of a new array and looping over the original. Doing this kind of operation on a huge array could produce undesirable side effects like, harder on mobile batteries, long waiting, jank, etc. – Jessy Aug 31 '18 at 19:10
2
function myFunction(ID){ 
let index = this.myArray.findIndex(d => d.ID === ID); //find index in your array
        console.log('index==',index);
        if (index > -1) {
          console.log('remaving at',index);
          this.myArray.splice(index, 1);//remove element from array
        }
}

Note: Your array must have a property called ID... otherwise it will return -1 which means not found

Zia Khan
  • 188
  • 2
  • 9
1

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;
    };
supernerd
  • 379
  • 4
  • 13
1

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; 
    });
}
Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170
  • 1
    This is not "removing an item", this is "creating a new array without that item". Entirely different things. – Clashsoft Jan 15 '22 at 16:32
  • @Clashsoft, true, but people often prefer immutable calls. If you want , you can re-assign result to the same variable myArr=arrayRemove(myArr, elemToRemove). – Michael Freidgeim Jan 16 '22 at 05:43
1
_.pull(array,'a'); 

with a lib lodash https://lodash.com/docs/4.17.15#pull
complelte code:

import _ from 'lodash';
const allTagList = ['a','b','b']
_.pull(allTagList, b);
console.log(allTagList) // result: ['a']

PS: Lodash offer lots of operator, recommed to use it to simply your code. https://lodash.com

leonardosccd
  • 1,503
  • 11
  • 12
0

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]);
    }
  }
Yisi Tan
  • 309
  • 2
  • 5
0

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' ]
0

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.

Brackets
  • 464
  • 7
  • 12