Sarath
Sarath

Reputation: 1499

Remove Item 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 array result and i will set the array values 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 array value is not removing from Array items. All other values will perfectly remove using this function But the first value in array not removing from array. Can anyone please suggest the better option?

Upvotes: 3

Views: 136

Answers (3)

SimDion
SimDion

Reputation: 1080

A simple way to remove items from an array is the following :

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

use like this

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

Upvotes: 0

Aaron Hernandez
Aaron Hernandez

Reputation: 158

Try to used 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);

Upvotes: 0

Nikhil Batra
Nikhil Batra

Reputation: 3148

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

Upvotes: 1

Related Questions