DEV Community

Precious Longe
Precious Longe

Posted on

Manipulating Arrays in JavaScript

Manipulation of arrays refers to the numerous operations that can be performed on them, such as adding to an already declared array, deleting from it, or altering it in various ways. And these activities can be carried out through the use of methods.

Every JavaScript developer must interact with arrays at some time, and we'll go over the various ways these arrays can be modified here.
In this tutorial, you'll learn how to modify arrays using various methods in a step-by-step manner.

What are Arrays and How Do I Use Them?

An array is a variable that can contain elements of various data types, such as strings(" "), numbers (0....infinity), booleans(true/false) etc. There is no datatype discrimination in an array. These elements are saved in this variable, which can be accessed at any time.
Let's start by declaring our array.

var arrayName = []; //Initial array declaration
var resources = ["chrome","google","notion","youtube"]; 
Enter fullscreen mode Exit fullscreen mode

The first line declares an empty array, whereas the second declares an array of elements.

Methods for Array Manipulation

Now let's get to work and explain some of the various methods available to us.
As mentioned earlier, we can use methods to carry out some specific tasks such as adding and removing. So we will kick off with the methods for doing that.

var arr = ["JS",123,false,"or","today"]; //remember an array can contain any datatype
Enter fullscreen mode Exit fullscreen mode

push()

This method is used to add a new element to the end of the array thereby changing the length of the array.

var arr = ["JS",123,false,"or","today"];
arr.push("New-Element");
console.log(arr);//This will leave the array as ["JS",123,false,"or","today","New-Element"]
Enter fullscreen mode Exit fullscreen mode

pop()

This method is used to remove the last element of an array thereby changing the length of the array. It does not require any parameters.

var arr = ["JS",123,false,"or","today"];
arr.pop();//"today" will be removed from the array
console.log(arr);//['JS', 123, false, 'or']
Enter fullscreen mode Exit fullscreen mode

shift()

This method is used to remove the first element of an array, thereby changing the length of the array. It does not require any parameters.

var arr = ["JS",123,false,"or","today"];
arr.shift();//"JS" will be removed from the array
console.log(arr);//[123,false,"or","today"]
Enter fullscreen mode Exit fullscreen mode

unshift()

This method is used to add an element to the beginning of an array, thereby changing the length of the array. It requires the new array element to be added, as a parameter.

var arr = ["JS",123,false,"or","today"];
arr.unshift("react");//This will add "react" to the array
console.log(arr);//["react","JS",123,false,"or","today"]
Enter fullscreen mode Exit fullscreen mode

We just discussed the methods that we can use to add and remove elements from both the beginning and end of an array. How about adding and removing from any part of an array if we want to?
Let's look at which method(s) helps us achieve that!!

splice( )

This method is used to remove, remove and add or just add a new element(s) to an array. We can achieve any of these with this method. Let's get to understand how that can be achieved.

Syntax

array.splice(index, delete-Count, element1, ...,elementn);
Enter fullscreen mode Exit fullscreen mode

Index:

This specifies where to start removing elements from in the array.

delete-Count:

This parameter specifies the number of elements to be removed from an array.

elements1...,elementn:

Specifies the new elements to be added.
Now let's see this in action.

var arr = ["JS",123,false,"or","today"];
arr.splice(0,3);//This will remove JS,123 and false from the array
console.log(arr);//["or","today"]
Enter fullscreen mode Exit fullscreen mode

The index 0 contains element ["JS"] and the delete-count which is 3 deletes three elements ["JS",123,false] starting from index 0.
The code above is using splice() to remove elements from our array, now lets remove and replace elements.

var arr = ["JS",123,false,"or","today"];
arr.splice(2,3,"React","Angular","Vue","Codes");//this will remove false,"or" and "today" and add "React","Angular","Vue","Codes"
console.log(arr)//["JS",123,"React","Angular","Vue","Codes"]
Enter fullscreen mode Exit fullscreen mode

Here, our index is 2, which contains element [false] and our delete-count is 3. This deletes three elements starting from [false] and adds ["React","Angular","Vue","Codes"] to the array.
Finally lets only add elements without having to remove any.

var arr = ["JS",123,false,"or","today"];
arr.splice(4,0,"React","Angular");// this adds "React"and "Angular"  to the array.
console.log()arr//["JS",123,false,"or","today",today"];
Enter fullscreen mode Exit fullscreen mode

So we can see from the examples that at different points, we can have different numbers of parameters and when the delete-Count is set to 0, no element is removed. Take a few minutes to go through that again before we continue.

slice()

This method can be used to copy a specified number(s) of elements in an array and assigns them to a new array. This does not affect the original array.

Syntax

arr.slice(start,end)
Enter fullscreen mode Exit fullscreen mode

start:

This specifies where to start copying from.

end:

This specifies where the copying stops.

Lets see how that works.

var arr = ["JS",123,false,"or","today"];
arr.slice(1,4);//this will return [123,false,"or","today"]
console.log(arr);//["JS",123,false,"or","today"]
Enter fullscreen mode Exit fullscreen mode

Best practice is to always asign the Slice() to a new variable

var arr = ["JS",123,false,"or","today"];
let newArr = arr.slice(1,4);
console.log(newArr);// [123, false, 'or']
Enter fullscreen mode Exit fullscreen mode

That should be easy to grasp right?? Let's roll and learn some other methods.

toString()

This methods is used to convert every element in an array to strings. Remember we learnt earlier that an array can contain any datatype. So this method helps convert all datatypes in an array to strings separated by a comma.

var arr = ["JS",123,false,"or","today"];
console.log(arr.toString());// JS,123,false,or,today
Enter fullscreen mode Exit fullscreen mode

join()

This method is very similar to the toString() method, the difference is that here you can specify the separator. Remember toString separates the elements with a comma, here we are able to specify what to use as our separator.

var arr = ["JS",123,false,"or","today"];
console.log(arr.join("="));//JS=123=false=or=today
Enter fullscreen mode Exit fullscreen mode

concat

This method is used to combine two arrays or add more elements to an array then return a new array after adding.

var frontEnd = ["Javascript","React","Angular","Swift"];
var backEnd = ["Java","Ruby","Python","PHP"];
var fullStack = frontEnd.concat(backEnd);
console.log(fullStack);//['Javascript', 'React', 'Angular', 'Swift', 'Java', 'Ruby', 'Python', 'PHP']
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, we learned how to manipulate arrays in JavaScript using several methods. These methods we discussed will help you in performing simple tasks on arrays. Feel free to ask questions if you have any.


Please leave a comment or tweet me if you have any questions or recommendations! Make sure to follow me on social media!

Top comments (2)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Covering the basics is sometimes all we need to improve as a developer. Great solutions here.

Collapse
 
smartduke profile image
Precious Longe

Thank you, Andrew