Useful Array Methods every JavaScript developer should know and how to use them effectively.

Useful Array Methods every JavaScript developer should know and how to use them effectively.

As a developer, you work with data most of the time and it is your duty to understand how to structure that data and manipulate it when necessary. More also It is entirely dependent on you to choose the best and easy way possible to store and manipulate that data.

If you are a beginner and you don't understand what a data structure is and the types then click here to get a quick intro to JavaScript data structure and types.

Now, this article is not focused on all the data structures and types that can be found in JavaScript. We will be looking at the array data structure and some of its most useful methods for manipulating it.

At the end of this article, you should already understand

  1. What a JavaScript array is
  2. When to use an array
  3. JavaScript array methods
  4. How to manipulate an array using these methods

What is an Array

If you have ever written a manual list of items (this could be a to-do list or a list of stuff you need to get in the shopping mall) before, then understanding what an array is should be easy for you.

An array is a list-like object with so many methods to perform traversal and mutation. Did you get it? haha, I don't think you did so let's make it easy.

Remember that above I described an array as your manual shopping list and it is inevitably logical that we should be able to take out or cancel what we don't want from our list and also be able to add more things to the list right? we can even remove our first item and replace it with another item if we intend to make our list sequential right.

Let us look at some examples to get the idea straight.

How to make a coffee
  1. pour hot water inside a cup
  2. pour coffee inside the water
  3. Stir for 3 second
  4. coffee is ready for consumption

This is an example of how we write our manual list and we can decide we no longer want to stir our coffee and remove it or alternatively we may also decide we want to add milk to our coffee and therefore we go ahead and include it in our list.

This is all made possible because we have a means of mutating or traversing our list. Now in JavaScript arrays, this superpower we have on our list is called a method and we have lots of them in JavaScript.

Before we look at the method available for us to use, let us understand when we need to use an array first.

When to use an Array

If you understood what an array is with our list example above, then understanding when to use one will be like understanding how to boil water on a gas cooker.

Working with unstructured data can be difficult. You will agree with me that knowing the best way possible to structure it and refer to it anytime you need it will go along way to help you as a developer and also help you work faster and be more productive.

Now let's say you want to store the names of five students in a class, we can approach it in two ways. One will make our code more readable and hasten our job while the second might make us lose our job sooner.

// Names of the five students in a class

let student1 = 'Jon'
let student2 = 'Kay'
let student3 = 'June'
let student4 = 'Cally'
let student5 = 'Amaka'

console.log(student1)
// prints Jon to the console

Now from the example above, let us say we want to print out all the names of the five students or probably mutate it. That would be one hell of a job and that will probably make you the worst developer to ever walk the earth.

Just to get the sense of what I mean look at the image below

// Names of the five students in a class

let student1 = 'Jon'
let student2 = 'Kay'
let student3 = 'June'
let student4 = 'Cally'
let student5 = 'Amaka'

console.log(student1)
console.log(student2)
console.log(student3)
console.log(student4)
console.log(student5)
// prints Jon, Kay, June, Cally, Amaka to the console

Now let us consider the second way which is the better way to store this kind of stuff

let students = ['Jon','Kay','Cally','Amaka']
console.log(students)
// prints Jon, Kay, June, Cally, Amaka to the console

Just with two lines of code and we achieved the same result effectively. Now, this is one of the use cases where you consider using arrays.

Remember that above, I spoke of some superpowers given to us by JavaScript to do somethings to our arrays right? These superpowers are referred to as array methods.

JavaScript array methods

A method is simply a function that is a property of an object. in other words, methods allow us to get some information from objects. In our context arrays.

Just as we can easily tell the length of our manual list and also remove and add items to the list, we can also use array methods such as length (also be referred to as property), push and slice to perform similar operations on our array.

There are so many array methods to consider but since we won't be covering them in this post, you might as well get acquainted with them here

For this post, we will be considering ways we can do something to each item in our array separately using For Loop as well as some of the most popular methods introduced in ES6 such as Map and filter

How to Manipulate Arrays with these methods

When I started writing JavaScript, I was first introduced to For Loops as a way to iterate over things and I used this extensively on anything I wanted to iterate over, be it a string or an array, for me it was like the holy grail. But I later found a better and cleaner way to do some things without my almighty For Loop.

Let us look at a use case of using For Loop to add '!' to each name in our student array.

Let studentNames = ['Jon', 'Kay','Amaka','Ebuka','King']
for(let i =0; i<studentNames.length; i++){
        studentNames[i] =+'!'
}
 console.log(studentNames)
// ['Jon!', 'Kay!','Amaka!','Ebuka!','King!']

This looks pretty easy and straight forward. All we did was initialized a count

let i = 0

we incremented i

till it was the same length as our array, and for each increase in the value of i we used array indexing and added ! to each element in our array but we can all agree that you need to remember a lot of steps and if we encounter the case of nested arrays in our array, then things can get a little bit complicated easily.

Let us look at another way can manipulate our data using the same example with another array method using our usual for loop

let studentNames = ['Jon','Kay','Amaka','Ebere','Ebuka', 'king']

let newStudent = []
for (name of studentNames){

    newStudent.push(name + '!')
}

console.log(newStudent)
// [ 'Jon!', 'Kay!', 'Amaka!', 'Ebere!', 'Ebuka!', 'king!' ]

This is easier to understand than our first example. We started by initializing a variable newStudent that is an empty array and afterward iterated over our array, and for each item, in our array, we added ! to it and finally used an array method push to add it to our newly created array.

When I started working with array I asked my friend who was a more experienced dev at the time if there was a way I could also keep track of the index of an item in an array while iterating over it and he replied in affirmation. Let us look at it with an example for better clarification.

let studentNames = ['Jon','Kay','Amaka','Ebere','Ebuka', 'king']

newStudent = []
for (name in studentNames){
    console.log(name, studentNames[name])
    newStudent.push(studentNames[name] +'!')
}
console.log(newStudent)

//
'0' 'Jon'
'1' 'Kay'
'2' 'Amaka'
'3' 'Ebere'
'4' 'Ebuka'
'5' 'king'

[ 'Jon!', 'Kay!', 'Amaka!', 'Ebere!', 'Ebuka!', 'king!' ]
//

this is also a clear example and another you can iterate over an array while keeping track of the index. with this method, you can also traverse as well as mutate items in your array.

Before we look at the new way developers do it these days, let us look at one more method we could play with our array with a method known as forEach.

let also see some code samples

newStudent = []
studentNames.forEach(name => {
    newStudent.push(name+'!')
})

console.log(newStudent)

// [ 'Jon!', 'Kay!', 'Amaka!', 'Ebere!', 'Ebuka!', 'king!' ]

forEach method is a very popular way to mutate or traverse over an array. This method takes in a callback function with a parameter that represents a single item in the array and then does something to that item.

It also comes with an additional parameter called index that helps you keep track of the index of your item while iterating over the array

newStudent = []
studentNames.forEach((name ,index ) => {
    newStudent.push(`index: ${index} name: ${name + '!'}`)
})

console.log(newStudent)

// [
  'index: 0 name: Jon!',
  'index: 1 name: Kay!',
  'index: 2 name: Amaka!',
  'index: 3 name: Ebere!',
  'index: 4 name: Ebuka!',
  'index: 5 name: king!'
]

I know you have come a long way getting to this last part of the article and you have taken in a whole lot that needs to be digested. Well, you should pat yourself on the back for getting this far.

Now let us look at the most useful of them. I personally use this method amongst others each time I plan to do something to each item in an array. With your understanding of other array methods, you will see this as a savior and an answer to all your array problems.

So if you are as impatient as me and want to dive right in with me, then let's do it. Yay!!

The array method Map is a holy grail and performs more optimal than the array methods we have seen so far. let us look at an example with the same data

let studentNames = ['Jon','Kay','Amaka','Ebere','Ebuka', 'king']
newStudent = studentNames.map(studentName =>studentName + '!)

console.log(newStudent)

// ['Jon!','Kay!','Amaka!','Ebere!','Ebuka!', 'king!']

Looking at the above code you can agree with me that this second code is more readable and easy to write than the first.

What we did with the code above is we mapped over the array and for each item, in the array, we did something, which is adding ! to the end of each item. We can achieve more with this method but for the purpose of this post, we will use only the example above.

The map method also comes with an index parameter built-in just like we saw in our forEach method example.

The unique advantage of using the Map method is that unlike the other examples that are hardcoded, the map returns a new array which can be saved separated in another variable as you can see in the code snippet above, thanks to ES6 new syntaxes.

From the beginning of this article, we have been talking about how we can change our array or traverse over it.

What if there was a way we can conditionally return some part of our array instead of returning all of them or doing something to some of the items that passed specific conditions only, it will be great right?

Let's say we want to only add ! to the student names that only includes the letter K how can we achieve this? we could start by using one of our array methods and only add ! to an item that contains k and that will work for sure. But how efficient and optimal is that. I can tell you for a fact that for a small program it will run very fast, but as your program gets larger, the runtime increases.

Well, there is a built-in array method that can perform this task for us optimally and also abstracts away a lot of complexities.

Introducing to you the almighty filter method the holy sibling to the map method . Haha! that's just me being playful again

let us look at some example by solving the task above

let studentNames = ['Jon','Kay','Amaka','Ebere','Ebuka', 'king']
filteredStudent = studentNames.filter(studentName => studentName.toLowerCase().includes('k')).map(studentName => studentName + '!')

console.log(filteredStudent)

// [ 'Kay!', 'Amaka!', 'Ebuka!', 'king!' ]

Wow, I am always amazed by the wonders these two methods can do. We simply filtered our array with the filter method and returned only the items in our array that has the letter k and then mapped over each item with the map method and added ! to each.

You should note that this example above are just a mere introduction to these methods because they can really be used to achieve a lot more than what I have just shown above. Some of them can be used as a Higher other function (HOC), but we will discuss that in another article after this one.

Conclusion:

Now that you understand what an array is, how it is used, and how it can be manipulated and mutated, working with arrays will become easier for you.

You shouldn't stop here though, make more research, Google as much as you can and soon you will become a better JavaScript developer who writes clean and readable code. See you again soon