Let’s make it easy with ‘Ordertrooper’ Array Methods in Javascript

[filter, map, some, reduce]

As we well know, Javascript has native methods which make easier the work on arrays. Usually, when we are newbies in Javascript, we get used to go through the arrays using the ‘for’ loop, and that’s not bad, but in some cases we can make it more clear and efficient using the array methods.

Let’s get started…

Filter Method
As the name suggests, it filters the values of an array and returns a new array with the filtered values.

Sintaxis:

myArray.filter(callbackFunction)

callbackFunction: This function will be executed on every element of the array. This function includes a condition to filter the elements, and it returns only the elements for which the condition is true. Once the callback function finishes iterating all the elements of the array, it returns a new array with the new filtered values.

Code:

Result:


Map Method
It returns a new array with the results from calling a callback function on every element in this array.

Sintaxis:

myArray.map(callbackFunction)

callbackFunction: This function will be executed on every element of the array and inside the function we will indicate which values we want to return. Once the callback function finishes iterating all the elements of the array, it returns a new array with the new values.

Code:

Result:


Some
It returns True if the condition is true for some element of the array.

Sintaxis:

myArray.some(callbackFunction)

Code:

Result:

The isThereCrime value is true.

Reduce Method
It returns a cumulative value that was created and increased during every iteration process on each element of the array. How exactly does it work? At first sight, it seems to be a little complicated, but, in fact, it is pretty simple.

Sintaxis:

myArray.reduce(callbackFunction(cumulative, element), [initialval]);

The .reduce method recive two parameters:

1-callbackFunction (cumulative, element):
In the callback function the cumulative parameter is the value to be accumulated during the iteration of the array, and the second one is the element of the array that we are iterating.

2-initialval:
Optionally, this reduced method can receive an object as second parameter, and it will be employed as initial value for the cumulative value in the first iteration.

Let’s review some code…

Code:

Result:

The totalPrice value is: 61

As you can see, we accumulated the prices of elements of the array and it returned the total price in a single variable.

Ok, let’s look at another example:

In this case we have a sales array, we will group all its elements by the buyer’s name.

Result:


Note: These native methods accept optional arguments, but in order to explain everything briefly and easily, we used the basic syntax.

I hope this explanation helped you to expand your knowledge about array methods.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.