loading...

Process `string | string[]` item with `flat()` and `map()`

terrierscript profile image terrierscript ・1 min read

In some case, we meet string|string[] type (I meet this on next.js)

I found this can process simply with flat() and map() (Not flatMap())

function appendC(strOrArr : string | string[]) : string[] {
  return [strOrArr].flat().map( item => item + "c" )
}

appendC("a")  // ["ac"]
appendC(["aa", "bb")  // ["aac", "bbc"]

If you need generate array in map, you can use flatMap

function splitItems(strOrArr : string | string[]): string[]{
  return [strOrArr].flat().flatMap( item => item.split(",") )
}

splitItems("a,b")  // ["ac"]
splitItems(["aa,bb", "bb,cc")  // ["aac", "bbc"]

In addition, if you need process deep array (like [1,[1,2,[1,2,3],2],[3,2]]), you can use flat(Infinity)

[deepArray].flat(Infinity).map(...

Discussion

markdown guide