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: remove item from array javascript
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1);
}
console.log(array);
Example 3: js remove object from array by value
let originalArray = [
{name: 'John', age: 23, color: 'red'},
{name: 'Ann', age: 21, color: 'blue'},
{name: 'Mike', age: 13, color: 'green'}
];
let filteredArray = originalArray.filter(value => value.age > 18);
Example 4: remove element from array javascript
function removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
function removeItemAll(arr, value) {
var i = 0;
while (i < arr.length) {
if (arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
console.log(removeItemOnce([2, 5, 9, 1, 5, 8, 5], 5));
console.log(removeItemAll([2, 5, 9, 1, 5, 8, 5], 5));
Example 5: remove array elements javascript
let value = 3
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => item !== value)
console.log(arr)
Example 6: js remove item array
let originalArray = [1, 2, 3, 4, 5];
let filteredArray = originalArray.filter((value, index) => index !== 2);