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

前端 未结 16 1933
余生分开走
余生分开走 2020-11-27 09:26

How can I skip an array element in .map?

My code:

var sources = images.map(function (img) {
    if(img.src.split(\'.\').pop() === \"json         


        
相关标签:
16条回答
  • 2020-11-27 10:09

    Here's a utility method (ES5 compatible) which only maps non null values (hides the call to reduce):

    function mapNonNull(arr, cb) {
        return arr.reduce(function (accumulator, value, index, arr) {
            var result = cb.call(null, value, index, arr);
            if (result != null) {
                accumulator.push(result);
            }
    
            return accumulator;
        }, []);
    }
    
    var result = mapNonNull(["a", "b", "c"], function (value) {
        return value === "b" ? null : value; // exclude "b"
    });
    
    console.log(result); // ["a", "c"]

    0 讨论(0)
  • 2020-11-27 10:11
    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);
    

    The .filter(Boolean) will filter out any falsey values in a given array, which in your case is the null.

    0 讨论(0)
  • 2020-11-27 10:12

    Answer sans superfluous edge cases:

    const thingsWithoutNulls = things.reduce((acc, thing) => {
      if (thing !== null) {
        acc.push(thing);
      }
      return acc;
    }, [])
    
    0 讨论(0)
  • 2020-11-27 10:12

    I use .forEach to iterate over , and push result to results array then use it, with this solution I will not loop over array twice

    0 讨论(0)
提交回复
热议问题