In an array I want to find the index of a value and then remove that value. The constraint is that I have to use core JavaScript without any frameworks.
let array = [9,8,7,6,5,4,3,2,1];
How can I find the index of ‘4’ and remove it from the array using core JavaScript?
New contributor
Prabhat Kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
let array = [9, 8, 7, 6, 5, 4, 3, 2, 1];
// Find the index of the value '4'
let index = array.indexOf(4);
// array is valid length
if (index !== -1) {
// Remove the value at index
array.splice(index, 1);
}
console.log(array);
You don’t need to find the value from Index 4 in order to remove it, you can just blindly remove it using Array.splice()
let array = [9,8,7,6,5,4,3,2,1];
const indexFound = array.findIndex(el => el === 4);
console.log('Value at index 4 found:', indexFound);
array.splice(4);
console.log(array)