remove item in array by index javascript code example
Example 1: remove a particular element from array
var colors = ["red","blue","car","green"];
var carIndex = colors.indexOf("car");
colors.splice(carIndex, 1);
Example 2: javascript remove from array by index
array.splice(index, 1);
Example 3: array remove index from array
const array = [2, 5, 9];
const index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1);
}
console.log(array);
Example 4: remove one element using splice
fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
removeFruitByIndex(index: number) {
this.fruits = [
...this.fruits.slice(0, i),
...this.fruits.slice(i + 1, this.fruits.length),
];
}
removeFruitByValue(fruite: string) {
const i = this.descriptionsList.indexOf(fruite);
this.fruits = [
...this.fruits.slice(0, i),
...this.fruits.slice(i + 1, this.fruits.length),
];
}
Example 5: remove elemtns from an array with splice
var fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
document.getElementById("demo").innerHTML = fruits;
function myFunction() {
fruits.splice(2, 2);
document.getElementById("demo").innerHTML = fruits;
}