DEV Community

Sivakumar Mathiyalagan
Sivakumar Mathiyalagan

Posted on

Array Iteration Methods

forEach() :

1.This method accepts another function as an Argument(callback Function) to perform certain operation on the array it is iterating
2.To call any of the iteration method must check these criteria

  • must need an object to call the method
  • what argument need to be passed
  • what return type the iteration method provides

forEach method takes 3 arguments

  1. The item value
  2. The item index
  3. The array itself

And forEach method returns nothing

output:

map()

Unlike forEach method map method retuns a new Array
It doesnot mutate the original Array
If some index value is not defined in an array for Example
[1,2, ,3,4]

output:

flatMap()

This method transforms each element into an array, then flattens it one level
map method returns single value make the resultant array as a nested array
whereas flatMap removes the nested format one level deep by default
let's see with example

in map method:

output:

Using flatMap method:

output:

filter()

This method creates a new array with the filtered value based on the condition provided through call back function

output:

reduce()

This method reduce the array to single value
this runs from left to right but it does not alter the original array

this methos takes 4 arguments

  1. The total (the initial value / previously returned value)
  2. The item value
  3. The item index
  4. The array itself

output:

Top comments (0)