I know I can declare an array in JavaScript like this var miArray = [];
, I can also add elements with miArray.push(elemento);
.
But: How do I add or remove elements in a certain position?
I have seen that it exists splice()
and that it does both things (delete and add) but I don't quite understand how it works correctly with the examples I have found.
To add an element at a certain position:
To remove an item:
The general syntax is ( reference ):
...and returns an array with the elements that have been removed.
Note that the first position is 0.
Example using node.js interactive mode:
To add an element in a certain position of an array you have the splice function. Which modifies the array by inserting or deleting elements and returns the array of the elements that were removed (if any were removed). The first parameter is the index where you want to add and/or delete elements, the second the number of elements to delete and the following the elements to insert in the indicated position. Example:
The result of splice is an array of the removed elements, in this case ["Apple"] and fruits now contains Banana,Orange, Lemon,Kiwi ,Mango. As you can see, Lemon and Kiwi are inserted in position 2 of the array and as it is indicated that an element must be removed, it removes the one in position 2 at that moment, Apple.
In addition to push, which adds the element to the end of the array, there is the unshift function, which allows you to add one or more elements to the beginning of the array. Example:
The result of unshift is the number of elements in the array, and fruits now contain Lemon,Pineapple,Banana,Orange,Apple,Mango.
A very efficient way to remove elements from a list, especially if there are a lot of them, is to use
filter
. This method creates a new array with all the elements of the original array that pass a test; the test is a function that you pass as a parameter. For example, to get only the even elements of an array:To add data, another option in addition to the one commented by konamiman is the method
push
, which adds the value supplied as a parameter as the last element of the array:To remove you can use: