Home > Software engineering >  How to remove Comma from output element after mapping an Array in React js
How to remove Comma from output element after mapping an Array in React js

Time:10-11

I want the output like: Custom(F,T,S)

But output comes like,

enter image description here

My code:

'Custom' (${data.state?.days?.map((item) => item.day ? item.day : '')})

Thanks...........

CodePudding user response:

TL&DR :

'Custom'   (${data.state?.days?.filter((item) => !!item.day).map((item) => item.day)})

Array.map always transform all the entries of an array. In your case, you have some some item that don't have a "day". So, you create a new array with empty elements

First, you have to filter your array :

data.state?.days?.filter((item) => !!item.day)

Then map through it

data.state?.days?.filter((item) => !!item.day).map((item) => item.day)

CodePudding user response:

Looks like you have items without day, so filter them out:

[{day: 'M'}, {day: 'T'}, {day: 'W'}, {noday: 'T'}, {day: 'F'}].map((item) => item.day ? item.day : '').filter(s => s.length > 0)

CodePudding user response:

One approach is to use reduce.

data.state?.days?.reduce((acc, curr) => curr.day ? [...acc, curr.day] : acc, []).join()

Another one would be to use filter with map

data.state?.days?.map((item) => item.day).filter(Boolean).join()
  • Related