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

Leon Gaban picture Leon Gaban · Oct 15, 2015 · Viewed 10.3k times · Source

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

Answer

Barmar picture Barmar · Oct 15, 2015

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