Array Iteration

There are many useful array iteration functions.

Those functions are supported from ES6 (JavaScript 2015) and not by older versions such as Internet Explorer.

Some of the most common of them are:

  • forEach
  • map
  • flatMap
  • filter
  • every
  • some
  • find
  • reduce

All of this functions (except reduce) accept a callback with 3 arguments - value, index, arr.

  • value - the value of the element of the array
  • index - the index of the element
  • arr - the array itself

reduce callback accepts 4 arguments - total, value, index, array which we will look at later.

forEach

Iterates the elements of an array.

It accepts a function as an argument which holds 3 parameters - value, index and array.

Let's look at the following example:

Output:

The code snippet prints all indexes and values of the array in a way specified in the callback function.

The arr argument is the iterated array - [4, 8, 7, 6, 3] but this parameter is rarely used.

map

Returns an array which elements are modified in the callback.

Output:

flatMap

Similar to map but we can add more elements to the array if we return array.

Let's compare map and flatMap via the following example:

Output:

When the map callback returns array, then the element of the returned array is an array - like [4, 0, 0].

When the flatMap callback returns array, then it's element are added to the returned array as separate elements - like 4, 0, 0.

filter

Allows filtering specific elements.

if the callback returns true - the element will be present in the returned array.

If the callback returns false - it will not be present.

For example we can filter the array to return only the even numbers:

Output:

every

Allows checking if all elements match certain condition.

if all of the elements match the condition in the callback (to return true), then the every function returns true.

If one or more of the elements don't match the condition in the callback (to return false), then the every function returns true.

For example we can check if all of the elements in the array are even:

Output:

some

Allows checking if at least one of the elements match certain condition.

if at least one the elements match the condition in the callback (to return true), then the some function returns true.

if neither of the elements match the condition in the callback (to return true), then the some function returns false.

Output:

find

Finds the first element of array that matches certain condition (the callback to return true).

If no element matches the condition it returns undefined.

Output:

reduce

Accumulates a single value based on a callback function.

It has 2 arguments - the callback and the initial value.

The callback accepts 4 arguments - total, value, index, array in which total is the accumulated value.

An example of function summing array elements with console.logs for explanations:

Output: