Javascript array methods made easy (Part I)

Thidasa Pankaja Paranavitharana
3 min readJul 20, 2019

--

Today I’m going to look at 5 of the most used/useful javascript array methods. So, let’s get started.

map( )

This executes given function on every element of the array and return a new array.

Lets’ say we have an array which contains numbers. We need to multiply each number by two. So, we can use map() to do that.

array.map()

*** map( ) always returns a new array.

filter( )

This method creates and returns a new array with the elements which satisfies the condition in the given function.

Let’s say we have an array of numbers and we want to filter out only the even numbers. For that, we can use the filter() method.

array.filter()

Here evenNumbers array is a new array which contains an array of items which passed the condition in the provided function.

**If there are no elements which satisfy the condition, it returns an empty array.

reduce()

This array method considered as an accumulator function. This returns a single value.

Your reducer function’s returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array and ultimately becomes the final, single resulting value. — MDN

array.reduce()

Let’s say we have an array of the score of each player from a cricket match. If we want to get the total score, we can use reduce() method to do that providing the initial value as the second argument. So, in the above example, we have provided 0 as the initial value.

some( )

This method can be used to check if any item (even a single one) of the array satisfies the given condition.

Let’s say we have an array of numbers and we want to know if it contains an even number. For that, we can use some() method. It returns true if any of the numbers is an even number.

array.some()

Here the numberListOne array contains one even number so it returns true.
The numberListTwo array contains multiple even numbers so it returns true.
And the numberListThree array does not contain any even number so it returns false.

*** One interesting thing about this method is when the condition is met the method stops and returns true. So, in containsListTwo function, it does not evaluate numbers after the number 12 at index 4 (meaning it does not care if there’re multiple even numbers, it stops evaluating them as soon as it satisfies the condition with the first even number in the array).

every( )

This is quite same as some() except this method evaluates all the elements in the given array.

array.every()

Here in the above example, the numberListOne array contains multiple even numbers and an odd number. So, allEvenNumbersOne returns false as it evaluates the whole array. The numberListTwo array contains even numbers only. So, allEvenNumbersTwo returns true.

Useful Links

This is my first medium article. I hope you find this useful. If you do, please share and give some claps. 👏🏽

--

--