Javascript 101: A Guide to Array Methods in Javscript

After having looked at some of the most important string methods last week, this post will take a closer look at arrays and their Javascript methods.

Becoming comfortable with the various methods of data types in Javascript will greatly improve your problem-solving skills. It'll help you to write more readable, concise and performant code for the frontend and backend of your web applications.

If you are hearing about arrays as a data type for the first time, you should take a step back and read up on the foundations of data types in Javascript first.

array.slice( )

This method allows you to take a "slice" of data from your original array and save this slice to a new array. The method takes two numbers as arguments. The first one to specify the start of the slice, the second one to specify the end. Remember, that we start counting our array data at 0.

var colors = ["red", "blue", "green", "yellow"]
var newColors = colors.slice(2,4)
console.log(newColors) // logs ["green", "yellow"]
console.log(colors) // logs ["red", "blue", "green", "yellow"]

The original colors array remains untouched here.

array.splice( )

array.splice() is another method to create a new array from elements of an existing array. Even though this method sounds similar to array.slice(), its behaviour is a bit different. Once again, the method takes two numbers as arguments. The first number defines the start of the splice, the second one defines the number of elements that are going to be spliced.

Have a look at the previous example - here we wrote colors.slice(2,4) and specified the start and end values, to slice ["green","yellow"] from the array. Now for splicing it we would write colors.splice(2,2) as we want to start at the second position and splice exactly two elements. The result would be the same: ["green","yellow"]. Let's take a look at another example:

var users = ["Anna", "Ben", "Sarah", "Jim", "John"]
var latestUsers = users.splice(3,2)
console.log(latestUsers) // logs ["Jim", "John"]
console.log(users) // logs ["Anna", "Ben", "Sarah"]

Whoa! Wait a second, calling users.splice(3,2) actually permanently removed those two users Jim and John from our main users array. This didn't happen for our colors.slice() method - the original array remained the same even after we had created a sliced array from it. It's important to be aware of this behaviour as it might affect your code in unexpected ways.

Similarly to strings, arrays can also make use of the .indexOf() method. This opens up some interesting ways to use .splice() in our code. Let's assume our user "Sarah" wants to leave us forever and deletes her account. We don't know exactly where in our array her username was stored - what can we do?

var users = ["Anna", "Ben", "Sarah", "Jim", "John"]
users.splice(users.indexOf("Sarah"), 1)
console.log(users) // logs ["Anna", "Ben", "Jim", "John"]

users.indexOf("Sarah") will return the index of "Sarah" in our array (2). The second parameter tells our method to remove exactly one element. The result is our updated array of users.

array.push( ) and array.pop( )

So now that we have looked at users leaving our precious application, we need to look at a method to add new items to our array. array.push does just that.

var users = ["Anna", "Ben", "Jim", "John"]
console.log(users) // logs ["Anna", "Ben", "Jim", "John", "Spiderman]

We have looked at arrays containing strings in the last example. However, you can push any kind of data type to your array. Have a look at this messy example below:

var stuff = ["purple", 123.312, "chicken", ["nested", "array"]]
stuff.push({name:"harry", profession:"wizard"})
// logs ["purple", 123.312, "chicken", ["nested","array"], 42, {name:"harry",profession:"wizard"}]

We can also push multiple values at the same time

var users = ["Anna", "Ben", "Jim", "John"]
users.push("Peter", "Bob", "Jenny")
console.log(users) // logs ["Anna", "Ben", "Jim", "John", "Peter", "Bob", "Jenny"]

array.pop() is the evil twin of array.push - it will simply remove the last element of the array.

var users = ["Anna", "Ben", "Jim", "John"]
console.log(users) // logs ["Anna", "Ben", "Jim"]
console.log(users); // logs ["Anna"]

If for any kind of reason you want to save this removed value, you can assign it to a variable

var users = ["Anna", "Ben", "Jim", "John"]
var removed = users.pop()
console.log(users) // logs ["Anna", "Ben", "Jim"]
console.log(removed) // logs "John"

array.shift( ) and array.unshift( )

So now we can add and remove elements at the end of our array. What if we want to do the same thing but at the beginning of our array? This is exactly what array.shift() and array.unshift() were created for. array.shift() is the equivalent to array.pop() and removes one element from the beginning of our array.

var users = ["Anna", "Ben", "Jim", "John"]
console.log(users) // logs ["Ben", "Jim", "John"]
var saved = users.shift()
console.log(users) // logs ["Jim", "John"]
console.log(saved) // logs "Ben"

The second time we called users.shift(), we saved our removed value "Ben" to a variable, just like with array.pop(). array.unshift() works just like array.push() and adds elements at the beginning of your array.

var users = ["Anna", "Ben", "Jim", "John"];
console.log(users) // logs ["Timmy", "Anna", "Ben", "Jim", "John"]
console.log(users) // logs ["Bob", "Sarah", "Timmy", "Anna", "Ben", "Jim", "John"]

array.join( )

With all the methods we've looked at so far it should be clear to you that arrays are great to work with. However, sometimes we might want to output the contents of an array to our users. array.join() is a method that helps us to easily convert our array content to a string. array.join() takes a string as an argument, which will be used to connect all the elements of the array.

var myArray = ["running", "coding", "reading", "surfing"]
var myString = myArray.join(", ")
console.log("my hobbies are " + myString)
// logs "my hobbies are running, coding, reading, surfing;

array.reverse( )

This method is pretty much self-explanatory. It'll reverse the order of all elements within the array.

var myArray = ["running" ,"coding", "reading", "surfing"]
console.log(myArray) // logs ["surfing","reading","coding",running"]

In combination with other methods and the previously learned string method str.split(), we can use array.reverse() to reverse strings too.

var myString = "reverse me"
var reversedString = myString.split('').reverse().join('')
console.log(reversedString) // logs "em esrever"

What we did here is chain multiple methods together. This is a nice way to reduce the complexity and length of your code. First, we are splitting the string (which will create an array), then we reverse this array and finally join it back together. The final result will again be a string, which is then assigned to our variable reversedString.

array.sort( )

The last array method we will be looking at in this post is array.sort(). This method will sort strings in your array alphabetically.

var myArr = ["Bob", "Sarah", "Timmy", "Anna", "Ben", "Jim", "John"]
// logs ["Anna", "Ben", "Bob", "Jim", "John", "Sarah", "Timmy"]

If we wanted to sort the array from Z-A instead of A-Z, we could simply combine this method with array.reverse.


If you want to use array.sort() with numbers however, you will run into trouble. Let's try sorting a simple array with numerical values.

myArr = [1, 5, 200, 30, 29, 24, 12];
// logs [ 1, 12, 200, 24, 29, 30, 5 ]

Wait a second, what happened here? To understand this behaviour of our sort method, we have to go back to the basics about data types and operators. The sort function will consider your numbers as strings as therefore only look at the first character of each number and order them accordingly. So in the eyes of our function, the array now looks like [1,1,2,2,2,3,5]. If we really want to compare the value of numbers in our sort function, we need a compare function.

This is not yet the time to discuss how to write your own logic in a compare function. For now, you should know that there are two compare functions that will allow you to sort numbers in an ascending or descending order:

myArr = [1, 5, 200, 30, 29, 24, 12]
myArr.sort(function(a, b){return a - b})
// ascending order
// logs [ 1, 5, 12, 24, 29, 30, 200 ];
myArr.sort(function(a, b){return a + b})
// descending order
// logs [ 200, 30, 29, 24, 12, 5, 1 ];

And this concludes another post about the fundamentals of Javascript. This list of array methods is not yet complete. We are missing some of the more advanced methods, also referred to as higher order functions -,array.forEach(),array.reduce() and array.filter(). These methods are highly versatile and a bit more complex than the methods we've looked at so far. That's why they deserve their own post in the near future.

Until then, please let me know if this post was helpful for you and which topics you'd like me to speak about next.

Further Reading: w3schools array reference MDN array reference