skip to Main Content

In the map() and filter functions(), is the iteration variable implicitly defined in it? or we can also explicitly define a variable to iterate through the array?

const numberArray = [1, 2, 3, 4, 5];

 const res = numberArray
.map(number => number * 2)
.filter(number => number > 5);

console.log(res);

Regarding declaration of iteration variable in Maps and Filters, how we can define it?

2

Answers


  1. The map and filter methods have the same parameters: element, index and reference to the source array. In your case you use only the first argument. You can give any name to the arguments, the main thing is to keep their order. Accordingly, you define «variable» names when you declare your arrow function inside map or filter. The variable represents the current element of the array at each iteration.

    Example with other names:

    const res = numberArray
      .map(num => num * 2) // You can use 'num', or any other name
      .filter(val => val > 5); // Similarly, 'val' is just a placeholder
    
    Login or Signup to reply.
  2. First i would recommend you to read the doc first:

    map, filter

    The callback function implicitly defines the iteration variable number in the map and filter functions.
    The callback function has 3 params:

    element
    The current element being processed in the array.

    index
    The index of the current element being processed in the array.

    array
    The array map() was called upon.

    number here is the first param,

    Maybe below is more obvious to you:

    const numberArray = [1, 2, 3, 4, 5]
    
    const res = numberArray.map(function(number) {
      return number * 2
    }).filter(function(number) {
      return number > 5
    })
    
    console.log(res)
    

    Regarding how to implement the map by yourself:

    map

    const numberArray = [1, 2, 3, 4, 5]

    const res = []
    for (let i = 0; i < numberArray.length; i++) {
      const number = numberArray[i] * 2
      if (number > 5) {
        res.push(number)
      }
    }
    
    console.log(res)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search