How can I skip an array element in .map?
My code:
var sources = images.map(function (img) {
if(img.src.split(\'.\').pop() === \"json
To extrapolate on Felix Kling's comment, you can use .filter() like this:
var sources = images.map(function (img) {
if(img.src.split('.').pop() === "json") { // if extension is .json
return null; // skip
} else {
return img.src;
}
}).filter(Boolean);
That will remove falsey values from the array that is returned by .map()
You could simplify it further like this:
var sources = images.map(function (img) {
if(img.src.split('.').pop() !== "json") { // if extension is .json
return img.src;
}
}).filter(Boolean);
Or even as a one-liner using an arrow function, object destructuring and the && operator:
var sources = images.map(({ src }) => src.split('.').pop() !== "json" && src).filter(Boolean);