To remove a specifc item from an array we make use of the indexOf and splice functions
indexOf : The indexOf ( search_element ) function returns the first index where a given element can be found in the array.
Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β It returns a -1 if the element is not present.
splice : The splice ( start, delete_count ) function modifies the contents of an array by removing or replacing the existing elements.
Javascript : Program to remove specific item from an array.
const arr = [20, 15,'alfa', 'beta', 9, 'gamma'];
console.log("Array contents")
console.log(arr);
console.log("Removing alfa from array");
const index = arr.indexOf('alfa');
if (index > -1) {
arr.splice(index, 1);
}
console.log("Array contents")
console.log(arr);
Output
Array contents
[ 20, 15, 'alfa', 'beta', 9, 'gamma' ]
Removing alfa from array
Array contents
[ 20, 15, 'beta', 9, 'gamma' ]
Β© 2019-2026 Algotree.org | All rights reserved.
This content is provided for educational purposes. Feel free to learn, practice, and share knowledge.
For questions or contributions, visit algotree.org
"Java is to JavaScript what car is to carpet. - Chris Heilmann"