In this article, we will discuss the methods to skip over elements in a map. The map() function in JavaScript is used to generate a new array by calling a function for every array element.
Note:
- map() method calls the function for every array element in order.
- map() does not execute for array element that has no values.
- map() does not change the original array.
There are various ways to skip over an element in the map:
Example 1: Adding the constraints inside the loop.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< title >
How to skip over an element in .map() ?
</ title >
</ head >
< body >
< p style="color: green;
font-size: 30px;">
GeeksforGeeks
</ p >
< p >[1,-1,-2,6,7,8]</ p >
< button onclick = "myFunction()" >
Click to skip negative values
</ button >
< p id = "demo" ></ p >
< script >
function display(num) {
if (num > 0) {
return num;
}
else {
return "null";
}
}
let values = [1, -1, -2, 6, 7, 8]
let filtered = values.map(display)
function myFunction() {
x = document.getElementById("demo")
x.innerHTML = filtered;
}
</ script >
</ body >
</ html >
|
Output:

Skip over an element in .map()
Example 2: Using the filter method.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< title >
How to skip over an element in .map() ?
</ title >
</ head >
< body >
< p style="color: green;
font-size: 30px;">
GeeksforGeeks
</ p >
< p >[1,-1,-2,6,7,8]</ p >
< button onclick = "myFunction()" >
Click to skip negative values
</ button >
< p id = "demo" ></ p >
< script >
function isPositive(value) {
return value > 0;
}
function display(num) {
return num;
}
let values = [1, -1, -2, 6, 7, 8]
let filtered =
values.map(display).filter(isPositive);
function myFunction() {
x = document.getElementById("demo")
x.innerHTML = filtered;
}
</ script >
</ body >
</ html >
|
Output:

Skip over an element in .map()
Example 3: Using the arrow function.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< title >
How to skip over an element in .map() ?
</ title >
</ head >
< body >
< p style="color: green;
font-size: 30px;">
GeeksforGeeks
</ p >
< p >Given< br >images = [{src: 1}, {src: 2},
{src: 3}, {src: 4}]< br >Skip src=3</ p >
< button onclick = "myFunction()" >Skip</ button >
< p id = "demo" >< br ></ p >
< script >
let images = [{ src: 1 }, { src: 2 },
{ src: 3 }, { src: 4 }];
let sources = images.filter(
img => img.src != 3).map(img => img.src);
function myFunction() {
x = document.getElementById("demo")
x.innerHTML = sources;
}
</ script >
</ body >
</ html >
|
Output:

skip over an element in .map()
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
02 Jun, 2023
Like Article
Save Article