Remove or Replace Array Elements in JavaScript


Let’s see how we can replace or remove elements in an array in javascript. We will use the Array indexOf() and splice() to find and remove/replace array elements:

let fruits = new Array("orange","apple","mango","strawberry","banana", "cherry");

// remove the element from array
fruits.splice(fruits.indexOf("mango"),1); // orange,apple,strawberry,banana,cherry

// splice in new element

The splice() method takes three parameters: the first parameter is required, as it’s the index where the splicing is to take place; the second, optional parameter is the number of elements to remove; the third parameter, also optional, is a set of the replacement elements (if any). If the index is negative, the elements will be spliced from the end rather than the beginning of the array:

let animals = ["cat","donkey","lion","cat"];

// splice in new element
animals.splice(-1,1,"monkey"); // cat,donkey,lion,monkey

If the number of elements to splice is not provided, all elements from the index to the end will be removed:

var animals = ["cat","walrus","zebra", "cheetah"];

// remove all elements after third index
animals.splice(3); //cheetah

The last parameter, the replaced value, can be a set of replacement elements, separated by commas:

let animals = ["cat","walrus","lion", "cat"];

// replace second element with two
animals.splice(2,1,"zebra","elephant"); // cat,walrus,zebra,elephant,cat

Removing or replacing one element is handy, but being able to remove or replace all instances of a particular element is even handier. The splice() method is used in a loop to replace all of the elements with a given value. The splice() method is used again, in a separate loop, to remove the newly spliced elements.

let charSets = ["ab","bb","cd","ab","cc","ab","dd","ab"];

// replace an element
while (charSets.indexOf("ab") != -1) {

// ["**", "bb", "cd", "**", "cc", "**", "dd", "**"]

// delete new element
while(charSets.indexOf("**") != -1) {
console.log(charSets); // ["bb", "cd", "cc", "dd"]

Leave a Reply

Your email address will not be published. Required fields are marked *