Removing or Replacing Array Elements - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Removing or Replacing Array Elements - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Saturday, December 22, 2018

Removing or Replacing Array Elements

Removing or Replacing Array Elements


Problem

You want to find occurrences of a given value in an array, and either remove the element or replace with another value.


Solution


Use the Array indexOf() and splice() to find and remove/replace array elements:

var animals = new Array("dog","cat","seal","walrus","lion", "cat");
// remove the element from array
animals.splice(animals.indexOf("walrus"),1); // dog,cat,seal,lion,cat
// splice in new element
animals.splice(animals.lastIndexOf("cat"),1,"monkey");
// dog,cat,seal,lion,monkey
console.log(animals.toString());

EXPLAIN

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 numberof 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:


var animals = ["cat","walrus","lion", "cat"];
// splice in new element
animals.splice(-1,1,"monkey"); // cat,walrus,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","lion", "cat"];
// remove all elements after second
animals.splice(2); // cat,walrus

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

var 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. In Example 2-1, an array is created with several elements, including multiple instances of a specific value. 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.

Using looping and splice to replace and remove elements

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

No comments:

Post a Comment

Post Top Ad