JavaScript - Delete First Occurence of Given Element from a JS Array
Last Updated :
17 Nov, 2024
Improve
These are the following ways to delete elements from a specified Index of JavaScript arrays:
1. Using indexOf() and splice() - Most Used
The indexOf() method finds the first occurrence of the element in the array, and splice() removes it at that index. This approach directly modifies the original array.
let a = [1, 2, 3, 4, 3, 5];
// Element to be deleted
let x = 3;
let i = a.indexOf(x);
if (i !== -1) {
a.splice(i, 1);
}
console.log(a);
Output
[ 1, 2, 4, 3, 5 ]
2. Using filter() method
The filter() method is used to create a new array that excludes the first occurrence of the element, without modifying the original array.
let a1 = [1, 2, 3, 4, 3, 5];
let x = 3;
let found = false;
let a2 = a1.filter(value => {
if (value === x && !found) {
found = true;
return false; // Skip first match
}
return true; // Include all other elements
});
console.log(a2);
Output
[ 1, 2, 4, 3, 5 ]
3. Using findIndex() with splice()
The findIndex() method returns the first occurrence of the element matching the condition, if it exists the splice() method is used to remove the element.
let a = [1, 2, 3, 4, 3, 5];
let x = 3;
let i = a.findIndex(value => value === x);
if (i !== -1) {
a.splice(i, 1);
}
console.log(a);
Output
[ 1, 2, 4, 3, 5 ]
4. Using for loop
The for loop manually iterates over the elements of the array to find and delete the first occurrence. The loop is stopped immediately after deleting the element.
let a = [1, 2, 3, 4, 3, 5];
let x = 3;
for (let i = 0; i < a.length; i++) {
if (a[i] === x) {
a.splice(i, 1);
break;
}
}
console.log(a);
Output
[ 1, 2, 4, 3, 5 ]