Top 10 array methods to learn to become a pro in JavaScript by Cules Coding. @thatanjan

Top 10 array methods to learn to become a pro in JavaScript

Arrays are very important in JavaScript. You will always have to deal with arrays. So, working with arrays efficiently is important. Today I will teach you the top 10 array methods that you should learn to become a pro in JavaScript. If you read till the end, I will teach you two extra methods.

Video tutorial

I have already made a video about it on my youtube channel.

Please like and subscribe to my channel. It motivates me to create more content like this.

Source Code

Top 10 method list

  1. forEach
  2. map
  3. filter
  4. reduce
  5. find
  6. findIndex
  7. some
  8. every
  9. sort
  10. splice

The first 9 methods are iterative functions. Iterative simply means looping. They are also Higher order functions. Don't worry if you don't understand Higher order functions. I will teach you higher order functions and arrow functions. If you understand them you skip that part.

Let's understand Higher order functions.

Higher order functions

A higher order function is a function that takes other functions as parameters.

1function hof(arg) {
2 console.log(arg)
3}
4
5hof('argument') // 'argument'

We know that we can pass anything as arguments to function calls like a number, string, boolean, etc.

But we can also pass functions as arguments.

1function hof(arg) {
2 hof() // 'callback'
3}
4
5hof(() => console.log('Callback'))

We have just passed a function as an argument and called the argument inside the hof function. That's why I have put the comment inside the hof function body.

The function that takes another function as an argument is called a higher order function. The function that has passed as an argument is called a callback function.

That's all you need to know about higher order functions for now.

Let's understand Arrow functions

Arrow functions (optional)

These functions are doing the same thing.

1function getSum(a, b) {
2 return a + b
3}
4
5const getSum = (a, b) => {
6 return a + b
7}
8
9const getSum = (a, b) => a + b
10
11const getSum2 = a => a + 10

The first one is the normal function with the function keyword. Other functions are arrow functions. They are the same thing except arrow functions are much cleaner and easier to write and read. Also, it solves some problems of our normal functions with the function keyword.

If you are just returning something from the function you don't need to use curly braces and the return keyword. And If you are using only one 1 parameter then you don't even have to use parentheses.

So, that's all you need to know.

Let's understand the JavaScript array iterative methods.

We will use the following data to understand the methods.

1const users = [
2 { name: 'John', age: 30 },
3 { name: 'Mary', age: 25 },
4 { name: 'Bob', age: 20 },
5 { name: 'Mike', age: 35 },
6 { name: 'Jill', age: 32 },
7 { name: 'Jack', age: 40 },
8 { name: 'Alice', age: 45 },
9 { name: 'Julie', age: 35 },
10 { name: 'Jane', age: 20 },
11 { name: 'Liz', age: 25 },
12]

forEach method

If I ask you to print all the user names, how would you do that?

Most probably like this:

1for (let i = 0; i < users.length; i++) {
2 const name = users[i].name
3 console.log(name)
4}

That's a lot of code. But we could do this with forEach method of JavaScript.

1// better way
2users.forEach(user => {
3 console.log(user.name)
4})
5
6// much better way
7users.forEach(user => console.log(user.name))
8
9// output:
10// John
11// Mary
12// Bob
13// Mike
14// Jill
15// Jack
16// Alice
17// Julie
18// Jane
19// Liz

Explanation:

  1. The forEach method will run a loop over the array.
  2. The callback function will be called on every single loop. And the current array item, index, and the array itself will be passed as an argument.
1users.forEach((user, index, array) => console.log(index, user.name))
2
3// output:
4// 0 John
5// 1 Mary
6// 2 Bob
7// 3 Mike
8// 4 Jill
9// 5 Jack
10// 6 Alice
11// 7 Julie
12// 8 Jane
13// 9 Liz

Behind the scenes it works like this:

1const callback = (item, index, array) => console.log(item)
2
3for (let i = 0; i < users.length; i++) {
4 const item = users[i]
5
6 callback(item, i, users)
7}

It might seem confusing. Don't worry. When I was learning about this, I was also confused. If you understand the forEach method, the rest of them will be easy.

map method

Let's create two new arrays of all user names and ages.

1const names = users.map(user => user.name)
2
3const ages = users.map(user => user.age)

Explanation:

  1. Map function creates a new array.
  2. Then it works just like the forEach method. Except you have to return something from the function on each loop.
  3. Whatever you will learn will be pushed to that array. In our case, it was name and age. Then the array is returned.

filter method

Let's get all the users whose age is more than or equal to 30.

1const over30 = users.filter(user => user.age >= 30)

Explanation:

  1. It works the same way as a map does. But instead of returning any value like number or string, you have to return a condition.
  2. That condition will be run on every item of the array. If the condition is true then that item will be pushed to an array.
  3. Finally the array will be returned.

Array method chaining

You can chain method one after another in one line.

Let's see the last example again. We want to get all users over 30 but only their names.

1// normal way
2const over30 = users.filter(user => user.age >= 30)
3const names = over30.map(user => user.name)
4
5// with method chaining
6const over30names = users.filter(user => user.age >= 30).map(user => user.name)

Warning about method chaining.

If you are handling large input, then method chaining can be inefficient. Because you have to loop over multiple times over a large number of inputs. Instead, you can use other methods.

1// with method chaining
2const over30names = users.filter(user => user.age >= 30).map(user => user.name)
3
4// with foreach loop
5const over30names = []
6
7users.forEach(user => {
8 if (user.age >= 30) over30names.push(user.name)
9})

reduce method

This one is a little bit different. Let's get the total age of all the users.

1let totalAge = 0
2
3users.forEach(user => {
4 totalAge += user.age
5})

With reduce method:

1const totalAge = users.reduce((total, user) => total + user.age, 0)

Explanation:

  1. reduce take two arguments.
    • Callback
    • initialValue
  2. In the callback function, total is the first argument. When reduce will run the first time total value would be the initial value.
  3. Then you have to return something from the callback. Whatever you will return will be passed as the total for the next loop. And it will keep going on.
  4. On the last loop, the total will be returned from the reduce method.

reduce method behind the scene:

1const callback = (total, item) => total + item.age
2
3let total = 0
4
5for (let i = 0; i < users.length; i++) {
6 total += callback(total, users[i])
7}

find method

Find the first user with the name 'John'

1const findUser = users.find(user => user.name === 'John')

Explanation:

  1. Similar to filter. Except it will return the first item that matches the condition and the loop will be stopped.
  2. If no item is matched, then undefined will be returned.

findIndex

Find the index of the first user with the name 'John'

1const findIndex = users.findIndex(user => user.name === 'Jane')

Explanation:

  1. Similar to findIndex. Except it will return the index that matches the condition and the loop will be stopped.

some

Check if there is any user with the name 'Mike'

1const someUser = users.some(user => user.name === 'Mike')

Explanation:

  1. It will check if any item matches the condition.
  2. Return value is boolean

every

Check if all users are adult

1const everyUser = users.every(user => user.age >= 18)

Explanation:

  1. Similar to some. But it will run the condition on every loop. If any item doesn't match the condition, then loop will be stopped.
  2. Return value is boolean

sort

Sort the users by their age.

1const sortUsers = users.sort((a, b) => a.age - b.age) // sort users by age
2const sortUsersDesc = users.sort((a, b) => b.age - a.age) // sort users by age in descending order

Explanation::

  1. When the sort() function compares two values, it sends the values to the compare function and sorts the values according to the returned (negative, zero, positive) value.

  2. If the result is negative a is sorted before b. If the result is positive b is sorted before a. If the result is 0 no changes are done with the sort order of the two values.

splice method

1users.splice(2, 0, { name: 'Jenny', age: 45 }) // add new user at index 2
2
3const removedUsers = users.splice(2, 1) // remove user at index 2 and returned

Explanation:

  1. splice method is really helpful. You can add or remove items at any index.
  2. At the first argument we have to pass the index from where we want to do operations.
  3. 2nd argument is for how many items you want to remove from the array.
  4. Then you can pass as many arguments as you want. They will be added to the given index.
  5. If you remove any item, then it will be removed from the function as an array.

These are the top 10 array methods you should know. Now it is time for bonus methods.

slice method

1const sliceUsers = users.slice(2, 5) // slice users from index 2 to index 5

Explanation:

  1. slice method returns a portion of the array.
  2. The First argument is the starting index. The last argument is for the ending index. But it will include that index item.
  3. For instance, if we pass 2 and 5 then the return array will include [2,3,4].

concat method

1const concatUsers = users.concat([{ name: 'Jenny', age: 45 }])

Explanation:

  1. concat method joins two or more arrays.
  2. It will create a new array and will be returned.

Shameless Plug

I have made an Xbox landing page clone with React and Styled components. I hope you will enjoy it. Please consider like this video and subscribe to my channel.

That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.

Contacts

Blogs you might want to read:

Videos might you might want to watch:

Previous PostHow to create typewriter effect with JavaScript
Next PostBuild a random password generator app with vanilla JavaScript