I am looking an easy and quick way to remove any element from an array in javascript, I can see there is way to add or remove new element in javascript using shift/unshift, but what about when I want to remove element from a specific position in an array? Something like this
arr.RemoveAt(0);
Thanks
First, I will give you answer using plain old Javascript to remove element in an array
To remove an element of an array at location(index) i:
arr.splice(i, 1); //remove 1 item at index 'i' of an array
To Remove every element (numberToremove
) of specific type, you need to loop
function removeAllInstancesOfItem(arr, item) {
for (var i = arr.length; i--;) {
if (arr[i] === itemToRemove)
arr.splice(i, 1);
}
}
It loops through the array backwards (as indexes and length will change when an item is removed) and removes the item if it's found.
let value = 4
let arr = [1, 2, 3, 4, 4, 5]
arr = arr.filter(item => item !== value)
console.log(arr);
// this will print [1,2,3,5]
But as ES6 is not supported in older browser like IE 10 or safari 10 version or below it, you would have to use BabelJS
You can also create custom method to remove item based on value, we will still use .splice() but it can be helpful
Array.prototype.removeByValue = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
}
var cars= ['bmw', 'audi', 'mercedes', 'jaguar'];
cars.removeByValue('audi');
console.log(cars);
//[bmw', 'mercedes', 'jaguar']
Hope it helps.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly