[filter, map, some, reduce]
Let’s get started…
As the name suggests, it filters the values of an array and returns a new array with the filtered values.
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.
It returns a new array with the results from calling a callback function on every element in this array.
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.
It returns True if the condition is true for some element of the array.
The isThereCrime value is true.
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.
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.
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…
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.
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.