Skip to main content

Command Palette

Search for a command to run...

Array iterator methods.

Published
2 min read
Array iterator methods.

Array in javascript is a type that stores different types in it as a list. It is really useful to store different data in a single variable name. Unlike C programming language array can store different datatypes under a single variable making it more flexible to use an array in javascript.

There are various iterator methods we could apply on arrays to play around with arrays and get the things as per our requirements.

  1. map() method returns the array populated with the values returned by calling the callback function from every value of the array applying. It does not manipulate the original array instead it returns a new array.

     const numbers=[1,2,3,4,5];
     let newArray=numbers.map((value)=>value*value);
     console.log(newArray);
     //expected outptu:[1,4,9,16,25]filter() method
    
    1. filter() method:

      filter() method returns an array with values that match certain conditions inside the executing part of callback function. It also does not manipulate the original array instead makes a new array of the values that passes the condition or that returns truthy

       const randomNumbers=[-1,2,-6,0,45,23];
       let newArray=randomNumbers.filter((number)=>number>0);
       console.log(newArray);
       //expected output:[2,45,23]
      
    2. reduce() method:

      reduce() method runs a callback function on each element in an array to pass in the returned value from the calculation on the preceding element.

      The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise, the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).

      To understand how reduce() method works we could look at the following example.

       let anArray=[3,5,6,7,8];
       let calculatedValue=anArray.filter((accumulator,currentValue)=>
       accumulator+currentValue);
       console.log(calculatedValue);
       //expected Output:29