Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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);
                @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 2, 2016 at 9:56
                @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 4, 2017 at 14:06
                @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, 2018 at 4:23
                This does not remove anything it simply filters. If the list actually needs to be modified this is not the way.
– user573434
                Jun 13, 2017 at 18:29
                @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, 2017 at 9:10
                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, 2017 at 3:22
                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, 2017 at 12:12
removeDocument(doc){
   this.documents.forEach( (item, index) => {
     if(item === doc) this.documents.splice(index,1);
                Best solution to remove without changing array reference AND with possibility to implement specific equality algorythm
– Sid
                Nov 21, 2017 at 10:43
                You can also use: this.documents.forEach( (item, index, array) => {      if(item === doc) array.splice(index,1);    });   Which can be a lot cleaner, especially when working with nested arrays.
– CGundlach
                Apr 15, 2019 at 15:03
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();
                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 8, 2018 at 20:00

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

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"]
                Just FYI, the splice method modifies the array (so in this case removes the last item) and returns the removed item(s), not the array itself.
– CGundlach
                Apr 16, 2019 at 6:55
                In order to delete the last element of an array, I'd use Array's pop method instead of splice.
– Iván Pérez
                Jan 26, 2021 at 11:10

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

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)];
this.items = this.items.filter(item => item.item_id !== item.item_id);
                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, 2019 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, 2019 at 18:36

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);
                    @shivamsrivastava I like the code to be immutable where is possible; because of that I was using const instead of let.
    – Radu Linu
                    Dec 18, 2020 at 12:45
    

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

  • It removes inline without creating a new object
  • 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));
    I think you have misused the word 'mutate' here because splice definitely mutates the original object – myol Oct 25, 2021 at 12:27 // 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; 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, 2018 at 19:10 Array.prototype.remove = function (element) { const index = this.indexOf(element, 0); if (index > -1) { return this.splice(index, 1); return this;
    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

    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

    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]);
    
    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' ]

    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; 
                    This is not "removing an item", this is "creating a new array without that item". Entirely different things.
    – Clashsoft
                    Jan 15, 2022 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, 2022 at 5:43
            

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.