Ismail Ismail - 2 months ago 46
Javascript Question

javascript skip element on .map()

How can I skip an array element in .map?

my code:

//map all sources of the images
var sources = json.images.map(function (img) {
if(img.src.split('.').pop() === "json"){//if extension is .json
game.loadSprite(img.src,false,function(){
console.log("sprite loaded!");
});
return null; // skip
}else{
return img.src;
}
});


this will return

["img.png", null, "img.png"]

Answer

Just .filter() it first:

var sources = json.images.filter(function(img) {
  if (img.src.split('.').pop() === "json") {
    game.loadSprite(img.src,false,function(){
        console.log("sprite loaded!");
    });
    return false; // skip
  }
  return true;
}).map(function(img) { return img.src; });