Why can't I remove item from this Array using slice or lodash remove?

13,244

Use .splice() to modify the array. .slice just returns the selected elements.

vm.storedViews.splice(i, 1);

_.remove() didn't work because the the second argument is not an index, it's a predicate function -- it removes all elements of the array for which the function returns a truthy value. It looks like the closest lodash function to .splice() is _.pullAt(). It takes a list of array indexes to remove, so you can use it for your case where you just want to remove one element:

_.pullAt(vm.storedViews, i);

Instead of your for loop you can use _.findIndex():

_.pullAt(vm.storedViews, _.findIndex(vm.storedViews, 'id', view_id));

If the IDs are unique, you can also use:

_.remove(vm.storedViews, 'id', view_id);
Share:
13,244
Leon Gaban
Author by

Leon Gaban

Investor, Powerlifter, Crypto investor and global citizen You can also find me here: @leongaban | github | panga.ventures

Updated on July 18, 2022

Comments

  • Leon Gaban
    Leon Gaban almost 2 years

    Using slice (In this situation I find the correct item in the Array, attempt slice, but the Array stays exactly the same):

    for (var i=0; i<vm.storedViews.length; i++) {
        if (view_id === vm.storedViews[i].id) {
            vm.storedViews.slice(i,1);
            // vm.storedViews = _.remove(vm.storedViews, i);
            break;
        }
    }
    
    console.log('vm.storedViews',vm.storedViews);
    

    Using _.remove all items end up being removed from my Array:

    for (var i=0; i<vm.storedViews.length; i++) {
        if (view_id === vm.storedViews[i].id) {
            // vm.storedViews.slice(i,1);
            vm.storedViews = _.remove(vm.storedViews, i);
            break;
        }
    }
    
    console.log('vm.storedViews',vm.storedViews);
    

    enter image description here

  • Barmar
    Barmar over 8 years
    I think this is my first foray into lodash. The documentation is very nice.
  • Leon Gaban
    Leon Gaban over 8 years
    Thanks! I love lodash, look at that :) replaced a for loop with a 1 liner!