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
- forEach
- map
- filter
- reduce
- find
- findIndex
- some
- every
- sort
- 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}45hof('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}45hof(() => 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 + b3}45const getSum = (a, b) => {6 return a + b7}89const getSum = (a, b) => a + b1011const 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].name3 console.log(name)4}
That's a lot of code. But we could do this with forEach method of JavaScript.
1// better way2users.forEach(user => {3 console.log(user.name)4})56// much better way7users.forEach(user => console.log(user.name))89// output:10// John11// Mary12// Bob13// Mike14// Jill15// Jack16// Alice17// Julie18// Jane19// Liz
Explanation:
- The forEach method will run a loop over the array.
- 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))23// output:4// 0 John5// 1 Mary6// 2 Bob7// 3 Mike8// 4 Jill9// 5 Jack10// 6 Alice11// 7 Julie12// 8 Jane13// 9 Liz
Behind the scenes it works like this:
1const callback = (item, index, array) => console.log(item)23for (let i = 0; i < users.length; i++) {4 const item = users[i]56 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)23const ages = users.map(user => user.age)
Explanation:
- Map function creates a new array.
- Then it works just like the forEach method. Except you have to return something from the function on each loop.
- 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:
- 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.
- 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.
- 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 way2const over30 = users.filter(user => user.age >= 30)3const names = over30.map(user => user.name)45// with method chaining6const 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 chaining2const over30names = users.filter(user => user.age >= 30).map(user => user.name)34// with foreach loop5const over30names = []67users.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 = 023users.forEach(user => {4 totalAge += user.age5})
With reduce method:
1const totalAge = users.reduce((total, user) => total + user.age, 0)
Explanation:
reduce
take two arguments.- Callback
- initialValue
- In the callback function,
total
is the first argument. Whenreduce
will run the first timetotal
value would be the initial value. - 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.
- On the last loop, the
total
will be returned from thereduce
method.
reduce
method behind the scene:
1const callback = (total, item) => total + item.age23let total = 045for (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:
- Similar to
filter
. Except it will return the first item that matches the condition and the loop will be stopped. - 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:
- 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:
- It will check if any item matches the condition.
- Return value is boolean
every
Check if all users are adult
1const everyUser = users.every(user => user.age >= 18)
Explanation:
- 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. - Return value is boolean
sort
Sort the users by their age.
1const sortUsers = users.sort((a, b) => a.age - b.age) // sort users by age2const sortUsersDesc = users.sort((a, b) => b.age - a.age) // sort users by age in descending order
Explanation::
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.
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 223const removedUsers = users.splice(2, 1) // remove user at index 2 and returned
Explanation:
splice
method is really helpful. You can add or remove items at any index.- At the first argument we have to pass the index from where we want to do operations.
- 2nd argument is for how many items you want to remove from the array.
- Then you can pass as many arguments as you want. They will be added to the given index.
- 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:
slice
method returns a portion of the array.- The First argument is the starting index. The last argument is for the ending index. But it will include that index item.
- For instance, if we pass
2
and5
then the return array will include[2,3,4]
.
concat method
1const concatUsers = users.concat([{ name: 'Jenny', age: 45 }])
Explanation:
concat
method joins two or more arrays.- 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
- Email: thatanjan@gmail.com
- LinkedIn: @thatanjan
- Portfolio: anjan
- Github: @thatanjan
- Instagram : @thatanjan
- Twitter: @thatanjan
Blogs you might want to read:
- Eslint, prettier setup with TypeScript and react
- What is Client-Side Rendering?
- What is Server Side Rendering?
- Everything you need to know about tree data structure
- 13 reasons why you should use Nextjs
- Beginners guide to quantum computers
Videos might you might want to watch: