Remove element from array using Javascript

I have one javascript array, I will store this array in local storage

 var result;     
 result = [1,2,3,4,5];
 localStorage.setItem('result', JSON.stringify(result));

      

Above is the result of the array and I have set the values โ€‹โ€‹of the array to local storage

function removeItem(Id){
    result= JSON.parse(localStorage.getItem('result'));// get array values from local Strorage
    var index = result.indexOf(Id);// find index position
    result.splice(index , 1); //and removing the Id from array
    localStorage.setItem('result', JSON.stringify(result));// result set to local storage
}

      

function call

var id = 1;
removeItem(id);

      

The first positioned value of the array is not removed from the array elements. All other values โ€‹โ€‹will be completely removed with this function. But the first value in the array is not removed from the array. Can anyone suggest a better option?

+3


source to share


3 answers


To remove the first element, you must use the index value = 0, not 1



+1


source


Try using this function.

function removeItem(arr) {
    var what, a = arguments, len = a.length, ax;
    while (len  > 1 && arr.length) {
        what = a[--len ];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}

      



For example:

removeItem(result,1);

      

0


source


A simple way to remove elements from an array is as follows:

// as a function
function removeitem(item, arr){
    var i; while( ( i = arr.indexOf(item)) != -1)arr.splice(i, 1);
}

      

use

var result;     
result = [1,2,3,4,5];
removeitem(1, result);

      

0


source







All Articles