Most used Array Methods explained with Example

Most used Array Methods explained with Example

If you are working with Javascript or have just started learning Javascript you might or will encounter Array methods. I found them very difficult at first to learn and understand. But learned them with the most basic and easy-to-understand examples.

Let's go through them again.

The most used array methods are .map() and .filter() .

What I will cover:

  • What an Array is?
  • How .map() and .filter() works with example.

Let's refresh what an array is:

A variable containing the data is called an Array.

const arr = ["Apple", "Mango", "Banana", "Grapes"];

Here arr is an Array containing data.

So now that we know what an array is let's learn what .map() and .filter() are and how it is used to manipulate array in Javascript.

.map()

The map() method creates a new array with the results of calling a function for every array element.

const number = [1, 2, 4, 6];
const double = number.map((x) => x * 2);

console.log(double);
// [2, 4, 8, 12]

Here we have an Array number that contains numbers as data.

We create a function double that executes the map() method.

Let's see the syntax of the map.

It takes a parameter element i.e x in this case(you can name it whatever you want). The element is mapping over each number of number array.

So all the numbers that were mapped i.e x got multiplied by 2 . Hence it multiplies each number by 2 from the number array and creates a new one with the result: [2, 4, 8, 12].

.filter()

As the name suggests it filters out the elements from an array and makes a new array out of it if the test is passed in the called function.

const number = [1, 2, 3, 4, 5];
const checkNum = number.filter((x) => x < 4);

console.log(checkNum);
// [1, 2, 3]

Taking the same number array for this.

The syntax is almost the same as the .map() method. It also takes a parameter x.

We passed a condition that checks if the numbers are less than 4. Therefore it creates a new array with all the numbers that are less than 4.

Also, both these methods are very important to learn if you are planning to learn React.

So this is how I learned and understood both these methods with simple examples. You can play around with these methods by changing the test/conditions in the function.

Thanks for Reading!

Check out my Twitter