Javascript: Remove Items from an Array with Splice()

11/1/2019 2:48:25 PM

In Javascript, to remove an item or items from an array, use the splice function.


//the array you want to modify
var array = ["hello", "asdfasdf", "world"];

//show initial array
console.log(array);

//get the index of the value you want to remove
var index_to_remove = array.indexOf("asdfasdf");

//use splice to remove that index, and return a new array
//splice returns the removed elements
//remove at index: index_to_remove, remove 1 value
var removed_elements = array.splice(index_to_remove, 1);

//show final array
console.log(array);

//show removed elements
console.log(removed_elements);


//no error is thrown if you remove an index that doesnt exist
//the returned object will be null
removed_elements = array.splice(75, 1);
console.log(removed_elements);


//no error is thrown if you try to remove too many items
//the returned object will be null
removed_elements = array.splice(0, 10);
console.log(removed_elements);