JavaScript Code to Add or Remove Specific Elements of an Array
By Stephen Bucaro
An array is an indexed collection of data elements of the same type. Elements are numbered
(indexes start at 0), and the elements can be accessed using their index. An array can contain
numbers, characters, strings, or arrays (an array of arrays). Every cell in an array must
contain the same data type. Arrays are very useful in programming because they can be used like a data base.
You can explicitly create and initialize an array using the declaration Keyword new, as shown below.
var NFLTeams = new Array("Cowboys", "Patriots", "Raiders", "Seahawks", "Eagles", "Giants");
Or you can implicitly create and initialize an array using just the array's name, as shown below.
var NFLTeams = ["Cowboys", "Patriots", "Raiders", "Seahawks", "Eagles", "Giants"];
Using the keyword new to create an array has several advantages; 1. It allows you to
pass a number to the constructor that lets you create an empty array of a specific size, as
shown below. 2. It creates more understandable and more easily maintainable code.
var NFLTeams = new Array(6);
Remove Specific Elements from an Array
Once you have created and initialized an array, you might want to add or remove elements
of the array. Shown below is an example of how to remove an element form an array.
var NFLTeams = new Array("Cowboys", "Patriots", "Raiders", "Seahawks", "Eagles", "Giants");
var a = NFLTeams.indexOf("Seahawks");
delete NFLTeams[3];
RESULT: ["Cowboys", "Patriots", "Raiders",, "Eagles", "Giants"]
Note that the indexOf method searches the array for the specified item, and returns
its index. Then the delete method is used to remove the element at that index. indexOf
returns -1 if the item is not found. If the item is present more than once, indexOf
returns the position of the first occurrence.
array.indexOf(item,start);
Optionally, you can provide and index where to start the search. Negative values will start
at the given position counting from the end, and search to the end.
array.splice(index, 1);
If you study the result shown above, you will note that the delete method leaves an empty element
in the array. This is great if you need the array to stay the same size. But if you want the array
to be smaller after removing elements, use the Spice method. Shown below is an example of
using the Spice method to remove an element form an array.
var NFLTeams = new Array("Cowboys", "Patriots", "Raiders", "Seahawks", "Eagles", "Giants");
var a = NFLTeams.indexOf("Seahawks");
NFLTeams.splice(a, 1);
RESULT: ["Cowboys", "Patriots", "Raiders", "Eagles", "Giants"]
Using the spice method, you pass it the index of the element to be removed and the
number of elements to be removed at the index.
array.splice(index, howmany);
|