DEV Community

terrierscript
terrierscript

Posted on

1

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

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(...

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay