JavaScript : Remove a specific item from an array

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.

  • start : The index at which to start modifying the array.
  • delete_count : An integer value specifying the number of elements in the array to remove from start.

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' ]


Copyright (c) 2019-2024, Algotree.org.
All rights reserved.