Skip to main content

Array iteration methods(map, filter, reduce)

@serverSerrverlesskiy

The JavaScript language has a clear preference for arrays over other data structures. They have a lot of convenient specific tricks, for example, a whole set of iterating methods: map, filter, reduce.

map

Create

The map () method creates a new с array with the result of calling the specified function⚙️ for each element of the array.

Syntax

Book

let new_array = arr.map(function callback( currentValue[, index[, array]]) {
// Returns the item for new_array
}[, thisArg])

The map method calls the passed callback function once for each element, in the order of their occurrence, and constructs a new array from the results of its call. The callback function is called only for array indices that have assigned values, including undefined. It is not called for missing array elements (that is, for indices that were never specified, deleted, or never assigned a value).

The function⚙️ callback is called with three arguments:

  • the value of the element,
  • element index
  • and the array through which the passage is carried out.

If the thisArg parameter was passed to the map method, it will be used as the this value when callback is called. Otherwise, the this value will be undefined. Ultimately, the value of this as seen from the callback function is determined according to the usual rules for defining this as seen from a function.

The map method does not modify the array for which it was called (although the function⚙️ can do that!).

The range of elements processed by the map method is set before the first call to the callback function. Items added to the array after the start of the map method will not be visited by the callback function. If the existing elements of the array are modified by the callback function, their values ​​passed to the function will be the values ​​at the time when the map method visits them. Deleted items will not be visited.

Examples:

Math

simple example

You have an array with many objects, each representing a different person. There can be a lot of data here: name, age, hair color and favorite character from the cinema, but at the moment all this is not required - you only want to get an array of passport numbers of these people in order to give them all conference passes.

Live Editor
Result
Loading...

In certain cases, you may need to display an array of objects with the selected keys as a string :

Live Editor
Result
Loading...

Creating an array of Fahrenheit values from an array of Celsius values:

Thermometer

An example with processing each element of an array with a given formula :

Live Editor
Result
Loading...

Displaying an array of numbers using a function that takes an argument :

Live Editor
Result
Loading...

filter

filter

The filter () method creates a new array with all the elements that have passed the check specified in the passed function⚙️.

The result of a filter is always an array. If a function⚙️ for an element returns true (or any" true "value), this element is included in the result, otherwise it is not included.

Syntax

write

let newArray = arr.filter(function callback(element[, index, [array]])[, thisArg])

Description

m

The filter() method calls the passed callback function once for each element present in the array and constructs a new array with all values ​​for which the callback function returned true or a value that becomes true when cast to boolean. The callback function is called only for array indices that have assigned values; it is not called for indexes that have been dropped or have never been assigned values. Array elements that have not been checked by the callback function are simply skipped and not included in the new array.

The function⚙️ callback is called with three arguments:

  • the value of the element;
  • element index;
  • the array through which the passage is carried out.

If the thisArg parameter was passed to the filter() method, it will be used as the this value when the function is called. Otherwise, the this value will be undefined. Ultimately, the value of this as seen from a function⚙️ is determined according to the usual rules for defining this as seen from a function⚙️.

The filter() method does not modify the array on which it was called.

The range of elements processed by the filter() method is set before the first call to the callback function. Items added to the array after the start of the filter() method will not be visited by the callback function. If the existing array elements change, the values ​​passed to the callback function will be the values ​​at the time when thefilter()method visits them. Deleted items will not be visited.

Example

math

Filtering out all small values

The following example uses filter() to create a filtered array with all elements greater than or equal to value, and all elements less than value removed.

Live Editor
Result
Loading...

Wow

reduce

count

The reduce method also runs in the context of an array and calls a function⚙️ for each element, but it also accumulates the results of all calls into a single value. This behavior can be controlled.

reduce is not meant to modify the elements of a collection like map. Its task is to calculate the "sum" of all elements in one way or another, and return it.

The resulting value can be anything: a number, a string, an object, an array - it all depends on the problem that the JavaScript developer is solving.

The reduce method takes 2 parameters:

  • a function, like map, which will be called sequentially for each element of the collection; is the initial value of the accumulator.

The function⚙️ also has 2 arguments:

  • the first is the accumulated value (accumulator);
  • directly an element of the array.

Syntax

array.reduce(function callback[, initialValue])

Description

describe

The reduce () method executes the callback function once for each element in the array, excluding voids, taking four arguments: the initial value (or the value from a previous callback), the value of the current element, the current index, and the array to iterate over.

The first time the function is called⚙️, the accumulator and currentValue parameters can take one of two values. If the initialValue argument is passed in the call to reduce (), then the value of accumulator will be equal to the value of initialValue and the value of currentValue will be equal to the first value in the array. If no initialValue is specified, accumulator will be equal to the first value in the array, and currentValue will be equal to the second value in the array.

If the array is empty and no initialValue argument is specified, a TypeError exception will be thrown. If the array consists of only one element (regardless of its position in the array) and the initialValue argument is not specified, or if the initialValue argument is specified, but the array is empty, then this value will be returned, without calling the function⚙️ callback ...

Initial battery value

hatchng

Let's figure out the initial value. In the example, it is equal to 0, since we are calculating the numerical value - the sum of the ages. In place of zero, there can be any other number / string (empty or not) / object / array - whatever value you start accumulating from. For example, let's combine the names of all friends in one line :

Live Editor
Result
Loading...

Here, the initial value was the string " Friends: ", to which the names of all friends were gradually added.

If you do not specify the original value explicitly, the first 1️⃣ element of the array becomes implicitly. In this case, the function⚙️ for it is no longer called.

Example

Sum all values in an array:

Live Editor
Result
Loading...

And the same thing in one line of code:

Live Editor
Result
Loading...

chaining

unity

JavaScript programming supports the convenient chaining pattern - combining multiple functions⚙️ into one chain with sequential transmission of the result.

All three parsed methods are called in the context of an array, and two 2️⃣ of them also return an array. Thus, it is very easy to combine them.

For example, let's calculate the total age of all boys :

Live Editor
Result
Loading...

Or we can collect the girls' passport numbers to buy them plane tickets to Las Vegas :

Live Editor
Result
Loading...

Conclusion

With these great features⚙️ the code becomes easier to read. So, below is a list of articles that go into more detail on this topic.

EnglishMoji!

Problems?

Problem

Write to Discord chat.

Questions:

Question

A function to be called for each element of an array?

  1. currentValue
  2. array
  3. callback

A method that creates a new array with the result of calling the specified function for each element of the array:

  1. map
  2. filter
  3. reduce

The resulting value of the reduce method can be:

  1. Number
  2. Array
  3. Anything

Summing all values ​​in an array is achieved by the method:

  1. map
  2. filter
  3. reduce

Optional parameter or value used as this when calling the callback function:

  1. array
  2. index
  3. thisArg

A method that creates a new array with all the elements that passed the validation specified in the passed function:

  1. map
  2. filter
  3. reduce

Combining several functions into one chain with sequential transfer of the result:

  1. unity
  2. chaining
  3. merger

In order to understand how much you learned this lesson, take the test in the mobile application of our school on this topic or in our telegram bot.

EnglishMoji!

  1. Simplify your JavaScript - use map, reduce and filter
  2. 15 useful javascript examples of map, reduce and filter
  3. Array.prototype.map()
  4. Array.prototype.filter()
  5. Array.prototype.reduce()

Contributors ✨

Thanks goes to these wonderful people (emoji key):


AlisaNasibullina


Dmitriy Vasilev

💵

Resoner2005

🐛 🎨 🖋

Navernoss

🖋 🐛 🎨