DEV Community

cisneros-a
cisneros-a

Posted on

Different Array Methods

We'll be going over a few different common array methods in JavaScript. They are fundamental and immensely helpful.

Array.map()

Array.map() method

What it does:

This method takes an array and does whatever action you would like to do to each index in the array. You'll see here that all we are doing is multiplying each number by 2.

What it returns:

An array of the same length with each mutated index is returned with this method.

Array.filter()

Array.filter() method

What it does:

This method takes an array and goes through each of items in the array and only returns those that evaluate to true. In this case, we are checking to see which numbers in the array are completely divisible by 2.

What it returns:

An array with each of the indexes that evaluated to true. In this case, those numbers were only 2 and 4.

Array.find()

Array.find() method

What it does:

This method is similar to Array.filter() in that we checking indexes in the array to evaluate to true. However, the difference here is that this method only finds the first instance that evaluates to true and returns only that.

What it returns:

If an item in the array evaluates to true, that will be returned. It can be a string, integer, object, etc. In our case, we checking for a number divisible by 2. The first one is 2.

Array.includes()

Array.includes() method

What it does:

This method only checks to see if the array includes the value that you pass as an argument in the method. So in our first example, we are checking for the number 4 and in the second example, we are checking for the number 7.

What it returns:

The includes method will always return a boolean (true or false). In our first example, we see that our nums array does include 4 so true is returned. In our second example, 7 is not in our array, so false is returned.

Array.every()

Array.every() method

What it does:

This method is checking that every item in the array evaluates to true. If any evaluate to false, then false is returned.

What it returns:

This method will always return a boolean. In our case, we are checking to see if every number is less than 3. Since we have at least one number that is equal or greater than 3, it will return false.

Array.some()

Array.some() method

What it does:

This method is checking that at least one item in the array evaluates to true. If any evaluate to true, it will return true.

What it returns:

Just like with Array.every(), this method will always return a boolean. Here, we are checking to see if at least one item in the array evaluates to true. Since some of the numbers in the array are less than 3, it will return true.

Here are just a few array methods that are available to us in JavaScript!

Top comments (0)