How to remove an element from an Array in Javascript?
I have an array of Strings, let's say an array of colors like ['red', 'green', 'blue'] and I want to remove a particular element from this Array, How can I do this in Javascript?
1 Answer
6 years ago by VD
1. ES6 and above ( Latest JavaScript )
let old_array = ['red', 'green', 'blue']
let element_to_remove = 'green';
let new_array = old_array.filter(ele => ele !=== element_to_remove);
console.log(new_array); // => prints [ 'red', 'blue' ]
2. To work with all versions of JavaScript ( For older browsers )
var old_array = ['red', 'green', 'blue']
var element_to_remove = 'green';
var index = old_array.indexOf(element_to_remove);
if (index > -1) { // safety check to see the element really exists in the array
old_array.splice(index, 1);
}
console.log(old_array); // => prints [ 'red', 'blue' ]
6 years ago by Karthik Divi