JavaScript Array Methods – Add and Remove Elements
Hello everyone, as promised. We come again with some more knowledge, this time bring JavaScript Array methods for Adding and Removing elements. If you didn’t read our previous lesson on Array basics, click on the link below and read it, so you will have a good idea about JavaScript arrays.
“JavaScript Array to make our life easy – Under the Hood Concepts”
Let’s start with some very useful javascript arrays methods for adding and removing elements from an array.
push()
We use this method to insert an element into an Array to the end. You need to give elements as parameters to this method like arr.push(element1,element2, and so on). This is a very useful method, let me show you how.
var language = ['English', 'Spanish', 'French']; console.log(language); //[ 'English', 'Spanish', 'French' ] language.push('Portuguese'); console.log(language); //[ 'English', 'Spanish', 'French', 'Portuguese' ] language.push('Hebrew', 'Chinese'); console.log(language); //[ 'English', 'Spanish', 'French', 'Portuguese', 'Hebrew', 'Chinese' ]
pop()
Its work is totally opposite from the push() method. This is to remove the last element from the array but unlike the push() method it doesn’t need any parameter. Let’s see the example.
var language = ['English', 'Spanish', 'French'];
language.pop();
console.log(language); // [ 'English', 'Spanish' ]
As we are talking about adding and removing the elements from the array. We have two more methods shift() and unshift(), but in my opinion, these methods are not widely used. I tell you the reason after their examples.
unshift()
Same like push() method, it is also used to insert the element into an array but towards the start. Its syntax same like push also unshift(element1, element2, and so on).
var language = ['English', 'Spanish', 'French']; console.log(language); //[ 'English', 'Spanish', 'French' ] language.unshift('Portuguese'); console.log(language); // [ 'Portuguese', 'English', 'Spanish', 'French' ] language.unshift('Hebrew', 'Chinese'); console.log(language); // [ 'Hebrew', 'Chinese', 'Portuguese', 'English', 'Spanish', 'French' ]
shift()
Same as the pop() method, it works to remove the element from an array but towards the beginning.
console.log(language); //[ 'English', 'Spanish', 'French' ] language.shift(); console.log(language); //[ 'Spanish', 'French' ]
As I told before, developers very less use this method, because there is a drawback in these two methods. Their processing time higher as if you add or remove any element in the starting, all the elements shift their position. And the index of every element will change unlike the push() and pop() methods as push() and pop() method do not impact the position of any other element in the array.
Now, you ask what to use if you want to add in the beginning and it is required. So we have another widely used methods splice() and slice()
splice()
This method is used to delete the item and same time you can add the element also. It always returns a new array of removed elements and if no elements removed it will return an empty array []. Its syntax is
array.splice(index, deleteCount, element1, element2, and so on);
First Parameter – Index of the element Where you want to change elements.
Second Parameter – Number of elements you want to delete
Remaining Parameters – Elements which you want to add in the array
var language = ['English', 'Spanish', 'French']; // Remove Spanish and add Portuguese at index 1 and it retern array of deleted elements var removedLanguages = language.splice(1, 1, 'Portuguese'); console.log(language); //[ 'English', 'Portuguese', 'French' ] console.log(removedLanguages); //[ 'Spanish' ] // Add Hebrew without removing anything at index 1 and return an empty array as nothing removed var removedLanguage2 =language.splice(1, 0, 'Hebrew'); console.log(language); //[ 'English', 'Hebrew', 'Portuguese', 'French' ] console.log(removedLanguage2); //[]
In the splice() method, deleteCount can only be 0 or a positive number but Index can be negative also. The negative index will be counted from the right side of the array and -1 will be considered as the last element of the array, -2 will be second last and so on. And the elements will be added before that element. Let’s see the above example with the negative index.
var language = ['English', 'Spanish', 'French']; language.splice(-1, 1, 'Portuguese'); console.log(language); //[ 'English', 'Spanish', 'Portuguese' ] // French removed and Portuguese added at index -1 (Last position) language.splice(-1, 0, 'Hebrew'); console.log(language); //[ 'English', 'Spanish', 'Hebrew', 'Portuguese' ] // Hebrew added before index -1 element without removing anything
In splice(), all the parameters are optional we can send as many parameters as we want, like array.splice(1,1), array.splice(1), array.splice().
If we use only two parameters, it will only perform remove function and not add any element.
var language = ['English', 'Spanish', 'French']; language.splice(1, 1); console.log(language); //[ 'English', 'French' ] // index 1 element "Spanish" deleted without adding anything language.splice(-1, 1); console.log(language); //[ 'English' ] // index -1 element"French" deleted without adding anything
var language = ['English', 'Spanish', 'French']; language.splice(1); console.log(language); // [ 'English' ] var fruits = ['Mango', 'Orange', 'Banana']; fruits.splice(0); // [] -empty array
var language = ['English', 'Spanish', 'French'];
language.splice(-1);
console.log(language); // [ 'English', 'Spanish' ]
slice()
This method is quite similar to the splice method but it will return a new array consisting of the elements which you want to keep and it will not affect the parent array in any way. Apart from this it also only takes 2 parameters.
array.slice(beginningIndex, endingIndex);
First Parameter – Index number from where you want to keep the elements
Second Parameter – Index number of the last element you want the keep + 1
suppose you have one array of 6 prime numbers [2,3,5,7,11,13], and you want a different array of three elements 5,7,11. Index of 5 is “2” and the index of 11 is “4”.
so, you will write – arrayName.slice(index of 5, index of 11 + 1); for above example array.slice(2, 4+1). Let’s see code example
var prime = [2, 3, 5, 7, 11, 13]; var primeNew = prime.slice(2, 5); // index of 3 is 2 and index of 11 is 4 console.log(primeNew); //[ 5, 7, 11 ] console.log(prime); //[ 2, 3, 5, 7, 11, 13 ]
You can see parent array is not affected by the slice() method, and it gave a totally new array.
slice() method also accepts the negative index but if both the parameters will be negative it will give the empty array.
var prime = [2, 3, 5, 7, 11, 13];
var primeNew = prime.slice(-1, -2);
console.log(primeNew); //[ ]
Let’s suppose the first parameter (beginning index) is positive. We have the same array as before [2,3,5,7,11,13] and we need the same result as last time 3,5,7 but this time using the second parameter (ending index) as negative. Then what will be the ending index?
before it was like
prime.slice(1,4) // in other words prime.slice(index of 5, index of 11 + 1)
Now try this,
prime.slice(1,-2) // you will get same result as prime.slice(1,4)
and
console.log(prime.length) // 6
So, can’t we say that
positive endingIndex - array.length = negative endingIndex
Let’s see some examples
var prime = [2, 3, 5, 7, 11, 13]; var primeNew = prime.slice(1, -4); var primeAnother = prime.slice(1,2) console.log(primeNew); // [3] console.log(primeAnother); // [3]
So if, sometimes you feel that negative index might confuse you, just add the array length into it and you will easily get what you want.
Same as splice(), slice() also has optional parameters. We can write array.slice(2,5) or array.slice(1) or array.slice()
array.slice() – it will return the completely new array with all elements as parent array because empty or undefined beginningIndex considered as 0. And array.slice(0) will also give the identical array as parent array.
var prime = [2, 3, 5, 7, 11, 13]; var primeNew = prime.slice(0); var primeAnother = prime.slice(); console.log(primeNew); // [ 2, 3, 5, 7, 11, 13 ] console.log(primeAnother); // [ 2, 3, 5, 7, 11, 13 ]
array.slice(-2) – It will give you the last two elements of the array. and as I told you before this value is equal to array.slice(array.length-2). So, in our above example array.slice(-2) = array.slice(4)
var prime = [2, 3, 5, 7, 11, 13]; var primeNew = prime.slice(-2); var primeAnother = prime.slice(4); console.log(primeNew); // [ 11, 13 ] console.log(primeAnother); // [ 11, 13 ]
These are some very useful JavaScript Array methods about Adding or removing elements. If you have any questions regarding this topic or any other javaScript topics please mention in the comment, so that I can promptly reply to you. And if you have not read our previous lessons of JavaScript Array, just click the link below and read it.
you can also visit the MDN website for more details.
JavaScript Challenge#2
Now, time for yet another javaScript challenge for you. I want a new array from the below array “prime”, new array name will be “prime10” with all the prime numbers greater than 10 and less than 20 (11,13,17,19). Use any of the methods I explained in this lesson above, which suits best for this challenge. Write your answers in the comment box. I will reply to you there, Let’s see who will be correct. Also if you can’t get the answer, don’t worry as you can check the answer in the link below.
Most Used JavaScript Array Methods – Finding The Elements
var prime = [2,3,5,7,11,13,17,19,23];
We will come again with some more knowledge very soon. Sign up with us so that you will not miss any of the future articles in the sequence of JavaScript tutorials. You can also follow us on our twitter or Facebook pages for all the future Lessons.
If you’re interested, Check out some other articles related to present crisis Coronavirus
Take care of yourself and your family!♥