Skip to content
Advertisement

Return no element from `Array.flatMap()` by if condition

I have this code:

  const myFunc = function (t) {
    return myArray.flatMap(clip =>
      (t < clip.start || t < clip.end) ? // Valid objects are returned in this *if* condition
        [
          { time: clip.start },
          { time: clip.end }
        ] : // how to return nothing in this *else* condition. Absolutely nothing?
        [
          {  },
          {  }
        ]
    )
  }

The above code used a ternary operator of condition ? exprIfTrue : exprIfFalse.

Currently I’m returning empty objects of { } in the case of exprIfFalse.

How can I return nothing in the case of exprIfFalse? I mean, I want absolutely nothing. I mean no array element.

Advertisement

Answer

Why cant you just return an empty array, any how Array.flat will remove those empty array from final code. In your case the array is not empty as [], its an array with two empyty objects as [{}, {}] that will produce two empty objects {}, {} in the final output after Array.flat

You have to return something from flatMap. If you return nothing, the corresponding nodes will be added as undefined. That wont be removed with Array.flat. Best option is to return an empty array as below.

Pseudo Code

const myArray = [1, 2, 3, 4, 5];
const myFunc = function (t) {
  return myArray.flatMap(clip =>
    (clip % 2 === 0) ? // Valid objects are returned in this *if* condition
      [
        { value: clip },
        { value: clip }
      ] : // how to return nothing in this *else* condition. Absolutely nothing?
      []
  )
}
console.log(myFunc());
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement