Remove Elements From A JavaScript Array
There are different methods and techniques you can use to remove elements from JavaScript arrays:
pop – Removes from the End of an Array
var ar = [1, 2, 3, 4, 5, 6]; ar.pop(); // returns 6 console.log( ar ); // [1, 2, 3, 4, 5]
shift – Removes from the beginning of an Array
var ar = ['zero', 'one', 'two', 'three']; ar.shift(); // returns "zero" console.log( ar ); // ["one", "two", "three"]
splice – removes from a specific Array index
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; var removed = arr.splice(2,2); /* removed === [3, 4] arr === [1, 2, 5, 6, 7, 8, 9, 0] */
filter – allows you to programatically remove elements from an Array
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; for( var i = 0; i < arr.length; i++){ if ( arr[i] === 5) { arr.splice(i, 1); } }
Share