How to skip over an element in .map()?

In JavaScript, we sometimes require to skip array elements while using the map() method. For example, we need to map value from one array to another array after performing some mathematical operations on the element only if the array value is finite.

In such cases, users can use the below approaches to skip over array elements while using the map() method.

Use the if-else statement

In the array.map() method, we can use the if-else statement to skip over the element. If the element fulfills the if-else statement condition, we need to return the element for mapping; Otherwise, we can return a null value.

Syntax

Users can follow the syntax below to use the if-else statement to skip over elements in the map() method.

array.map((number) => {
   if (condition) {
   
      // return some value
   }
   return null;
})

In the above syntax, we return some value if the condition of the if-else statement evaluates true; Otherwise, we return null.

Example 1

In the example below, we have created the array with numeric values. We aim to multiply every positive element with two and map them to the multiplier array. In the map() method, we check if the array is positive using the ‘element > 0’ condition, and if it evaluates true, we return the number after multiplying it by two.

In the output, users can see that when we return the null values, that array index appears empty.

<html>
<body>
   <h2>Using the <i> if-else </i> statement to skip over element in the array.map() method</h2>
   <div id = "output"></div>
</body>
<script>
   let output = document.getElementById('output');
   let array = [10, 20, 34, 4, 5, 6, 0, -1, 3, 2, 4, -2];
   let multiplier = array.map((number) => {
      if (number > 0) {
         return number * 2;
      } else {
         return null;
      }
   })
   output.innerHTML += "The final array after skipping the negative number in the map() method is - " + multiplier;
</script>
</html>