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.
function hof(arg) {console.log(arg)}hof('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.
function hof(arg) {hof() // 'callback'}hof(() => 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.
function getSum(a, b) {return a + b}const getSum = (a, b) => {return a + b}const getSum = (a, b) => a + bconst 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.
const users = [{ name: 'John', age: 30 },{ name: 'Mary', age: 25 },{ name: 'Bob', age: 20 },{ name: 'Mike', age: 35 },{ name: 'Jill', age: 32 },{ name: 'Jack', age: 40 },{ name: 'Alice', age: 45 },{ name: 'Julie', age: 35 },{ name: 'Jane', age: 20 },{ name: 'Liz', age: 25 },]
forEach method
If I ask you to print all the user names, how would you do that?
Most probably like this:
for (let i = 0; i < users.length; i++) {const name = users[i].nameconsole.log(name)}
That's a lot of code. But we could do this with forEach method of JavaScript.
// better wayusers.forEach(user => {console.log(user.name)})// much better wayusers.forEach(user => console.log(user.name))// output:// John// Mary// Bob// Mike// Jill// Jack// Alice// Julie// Jane// 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.
users.forEach((user, index, array) => console.log(index, user.name))// output:// 0 John// 1 Mary// 2 Bob// 3 Mike// 4 Jill// 5 Jack// 6 Alice// 7 Julie// 8 Jane// 9 Liz
Behind the scenes it works like this:
const callback = (item, index, array) => console.log(item)for (let i = 0; i < users.length; i++) {const item = users[i]callback(item, i, users)}
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.
const names = users.map(user => user.name)const 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.
const 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.
// normal wayconst over30 = users.filter(user => user.age >= 30)const names = over30.map(user => user.name)// with method chainingconst 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.
// with method chainingconst over30names = users.filter(user => user.age >= 30).map(user => user.name)// with foreach loopconst over30names = []users.forEach(user => {if (user.age >= 30) over30names.push(user.name)})
reduce method
This one is a little bit different. Let's get the total age of all the users.
let totalAge = 0users.forEach(user => {totalAge += user.age})
With reduce method:
const 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:
const callback = (total, item) => total + item.agelet total = 0for (let i = 0; i < users.length; i++) {total += callback(total, users[i])}
find method
Find the first user with the name 'John'
const 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'
const 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'
const 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
const 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.
const sortUsers = users.sort((a, b) => a.age - b.age) // sort users by ageconst 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
users.splice(2, 0, { name: 'Jenny', age: 45 }) // add new user at index 2const 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
const 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
const 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
Want to create your own blog? Well, I am creating a video series where you will learn about how to create a JAMstack blog with Nextjs and Chakra-UI.
Lessons
- Intro & Setup
- Build Homepage UI
- How our app will work
- MDX, MongoDB, Static Homepage
- Generate Static Blog Page
- Style Blog page with Chakra-UI and MDX-embed
- Build a real-time view counter
- Autocomplete search form with MongoDB Atlas Search Index
- Deploy application to Vercel
Demo
You can demo the website from here
Features
- Static Blog pages will make the website load faster.
- Blogs will have code blocks with syntax highlighting and many embed components like youtube videos, GitHub gist, Tweets, and so many other things.
- Autocomplete search feature for the blog posts.
- Real-time view counter and so on.
Please like and subscribe to Cules Coding. It motivates me to create more content like this.
That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.
By the way, I am looking for a new opportunity in a company where I can provide great value with my skills. If you are a recruiter, looking for someone skilled in full-stack web development and passionate about revolutionizing the world, feel free to contact me. Also, I am open to talking about any freelance project. I am available on Upwork
Contacts
- Email: thatanjan@gmail.com
- LinkedIn: @thatanjan
- Portfolio: anjan
- Github: @thatanjan
- Instagram (personal): @thatanjan
- Twitter: @thatanjan
- Upwork: @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: