Skip to main content

Command Palette

Search for a command to run...

Array Methods You Must Know

Updated
8 min read

What will we study?

So, today in this amazing blog we'll be learning some array methods if you have read my blog on Array Basics you'll have no problem here so if you don't know about array basics go ahead and check that out first

So today we'll be learning these some array methods which are as follows:

  • push() and pop()

  • shift() and unshift()

  • map()

  • filter()

  • reduce()

  • forEach()

Just like always blog will be in super easy language so that beginners feel right at home.

Don't take stress just sit back relaxed and have a cup of chai with you :)


Array methods you must know

push()

// Syntax

arrName.push(element)
  • This method is used to add an element to an array.

  • The element is added at the very end of the array.

const villians = ["Madara", "Light", "Muzan", "Sukuna"]

villians.push("Eren")

console.log(villians) // ['Madara', 'Light', 'Muzan', 'Sukuna', 'Eren']

pop()

// Syntax

arrName.pop()
  • This method is used to remove an element to an array.

  • The last element is removed and returned.

const villians = ["Madara", "Light", "Muzan", "Sukuna", "Eren"]

const notVillian = villians.pop()

console.log(villians) // ['Madara', 'Light', 'Muzan', 'Sukuna']

console.log(notVillian) // Eren

unshift()

// Syntax

arrName.unshift(element)
  • This method is used to add an element to an array.

  • The element is added at the very beginning of the array.

const villians = ["Madara", "Light", "Muzan", "Sukuna"]

villians.unshift("Eren")

console.log(villians) // ['Eren', 'Madara', 'Light', 'Muzan', 'Sukuna']

shift()

// Syntax

arrName.shift(element)
  • This method is used to remove an element to an array.

  • The first element is removed and returned.

const villians = ["Eren", "Madara", "Light", "Muzan", "Sukuna"]

const notVillian = villians.shift()

console.log(villians) // ['Madara', 'Light', 'Muzan', 'Sukuna']

console.log(notVillian) // Eren

Before you move to next

  • Before, you move to the next methods, keep that in mind that the methods we discussed above are easy but these are a little bit on harder scale.

  • Anyways, you don't have to worry because i have held your hand for this topic and i'll make you the master of this topic as well :)


map()

  • This method takes a callback (function) and applies that to all the elements in the array and returns a new array with the updated values.
// Syntax (Explicit Return)

arrName.map((currentValue, index, array) => {
    // code to perform 
    return currentValue
})


// Syntax (Implicit Return)

arrName.map((currentValue, index, array) => code to perform )
  • Here, in the explicit return we are using curly braces and that is why we have to type the keyword return. This is majorly used only when the code is long.

  • Here, in the implicit return we are using not curly braces and that is why we don't have to type the keyword return. This is majorly used only when the code is short.

  • In both the cases the currentValue demonstrates the current element on which the code is being applied. This is mandatory to use.

  • The index points to the index of the currentValue.

  • The array points the array on which you are using the map().

  • Note: These 3 parameters can be named anything there is no fixed rule for that but it is generally recommended to use the names which sync with the array that makes your code more readable and simpler.

// You are given with an array nums and you have to find the square of all the elements in the num. Do that and print whole array which have the squared values.

const nums = [1, 2, 3, 4, 5]

const newNums = nums.map((num) => num ** 2)

console.log(newNums) // output: [1, 4, 9, 16, 25]
  • Was that hard? Nope! even if it was it will not be.

  • Let's understand what map() does under the hood that would help us in understanding.

// What map did under the hood when we squared the whole array

const nums = [1, 2, 3, 4, 5]

const newNums = []

for (let index = 0; index > nums.length; index++) {
    const squared = nums[index] ** 2
    newNums.push(squared)
}

console.log(newNums) // output: [1, 4, 9, 16, 25]
  • See how easy it is basically map() takes your array and your code then runs a for loop on that array where it applies the code provided by you and then pushes those values to new arrays. That's it that's your map().

forEach()

  • If you understand map() then you understand forEach().

  • forEach also takes a callback and applies that to each and every element but the only difference is that it doesn't return a new array.

  • It is best preferred for performing an action for all elements (like logging, calling API, DOM).

// Syntax

arrName.forEach((currentValue, index, array) => {
    // Code to perform
})
  • The parameters are just same as the map(). You can use both implicit and explicit return in this too.

  • Let's understand with some code.

const nums = [1, 2, 3, 4, 5]

nums.forEach((num, index) => {
    console.log(`Value of index \({index}: \){num}`)
})

/*
Output:

Value of index 0: 1
Value of index 1: 2
Value of index 2: 3
Value of index 3: 4
Value of index 4: 5
*/
  • Let's see what it did under the hood in this case:
const nums = [1, 2, 3, 4, 5]

for (let index = 0; index < nums.length; index++) {
    console.log(`Value of index \({index}: \){nums[index]}`)
}
  • See how easy it was :)

filter()

// syntax

arrName.filter((element, index, array) => filter logic)
  • I won't explain syntax anymore it's just like the previous ones.

  • Filter returns a new array with only those elements who pass the filter logic code.

const nums = [3, 66, 34, 86, 12]

const aboveFifty = nums.filter((num) => num > 50)

console.log(aboveFifty) // output: [66, 86]
  • Let's see what i might have did under the hood.
const nums = [3, 66, 34, 86, 12]

const aboveFifty = []

for (let index = 0; index < nums.length; index++) {
    if (nums[index] > 50) {
        aboveFifty.push(nums[index])
    }
}

reduce()

  • Reduce is quite interesting, It returns just a single value according to the reducer you give.

  • It takes a callback that takes 2 parameters - accumulator and current value.

// Syntax

arrName.reduce((acc, val) => reducing logic, acc initial value)
  • Accumulator's initial value is optional, like it is mostly used but there are some cases where it is not used we'll have that in code examples let's see them.
// Find sum of all elements

const nums = [3, 66, 34, 86, 12]

const sum = nums.reduce((total, num) => total + num, 0)
// 0 is the initial value of the total and we are adding num in total.

console.log(sum) // output: 201



// Find the greatest among these

const greatest = nums.reduce((greatest, value) => greatest > value? greatest : value)
// See, if we provide 0 as the initial value then the logic will fail because we aren't updating it with this particular logic it compares greatest that is 0 to the current value if value is greater than make greatest = value else greatest would remain same.

console.log(greatest)
  • Don't worry if you didn't understood because reduce always goes from over the head at first time. Just have some more practice solve more questions.

An implementation

// Question: You are given an array of numbers your task is to multiply by 10 to each element and then filter out the array with having only those elements with value above or equal to 500. and lastly find the sum of the filtered array do this using method chaining.

// Method Chaining: You can use .map(), .filter(), .reduce() without creating new variables. The below code will tell you how to do that.


const nums = [2, 5, 1, 7, 9]

const sum = nums.map((num) => num * 10).filter((num) => num >= 500).reduce((total, num) => total + num, 0)

console.log(sum) // output: 2100
  • If you got that that's good.

  • If you didn't got that i won't spoon feed that, try to understand the code, dry run it, research more, solve more questions.


Conclusion

So, today we learned about basic array methods that we must know.

Key takeaways:

  • Learned methods like push(), pop(), shift(), unshift().

  • Learned some advanced methods as well like forEach(), map(), filter(), reduce().

  • Got some assignments to solve some questions on this (ask questions from ChatGPT or Claude but solve them on your own, that's a really strict guideline and you have to-have to do that).

Solve some questions and enjoy rest of your chai. I'll catch you up in the next blog ;)


JavaScript: Everything you should know

Part 6 of 26

This is your ultimate guide towards JavaScirpt, this series of articles include - JavaScript Operators: The Basics You Need to Know - Understanding Variables and Data Types in JavaScript - Template Literals in JavaScript - Control Flow in JavaScript: If, Else, and Switch Explained - Array Methods You Must Know - JavaScript Arrays 101 - Function Declaration vs Function Expression: What’s the Difference? - Arrow Functions in JavaScript: A Simpler Way to Write Functions - Understanding Objects in JavaScript - Spread vs Rest Operators in JavaScript - Destructuring in JavaScript - Map and Set in JavaScript - Understanding Object-Oriented Programming in JavaScript - Understanding the this Keyword in JavaScript - The new Keyword in JavaScript - The Magic of this, call(), apply(), and bind() in JavaScript - Array Flatten in JavaScript - String Polyfills and Common Interview Methods in JavaScript - Synchronous vs Asynchronous JavaScript - Callbacks in JavaScript: Why They Exist - JavaScript Promises Explained for Beginners - Promise Methods Explained: CID Analogy - Async/Await in JavaScript: Writing Cleaner Asynchronous Code - Error Handling in JavaScript: Try, Catch, Finally - JavaScript Modules: Import and Export Explained - The Part of Events You Never See The following 26 articles and topics are covered

Up next

Function Declaration vs Function Expression: What’s the Difference?

What are we going to Study? So, today we'll be learning about functions. We'll be covering the following topics: What are functions? Why do we need them? Function declaration Function expression D

More from this blog

L

Learning Tech

61 posts

A Blog with dozens of articles on different langauges as well as frameworks, This isn't just for you to learn, i crafted it thinking that this could be my future reference as well

It covers Networking, Web Development, Mobile Developement and very soon GenAI too!