Home > Enterprise >  How would I transform an array into a list
How would I transform an array into a list

Time:05-21

So basically, what I want is that if I have an array like this one:

["item", "item1", "item2", "item2", "item2"]

it should be changed into:

 - Item\n- Item1\n- Item2 (3x)

I have trying to figure this out for a few hours now and I can't think of anything, so I thought I should ask here. Help is very much appreciated.

CodePudding user response:

you can do something like this

const data = ["item", "item1", "item2", "item2", "item2"]


const result = Object.entries(
data.reduce((res, item) => ({...res, [item]: (res[item] || 0)   1}), {})
).map(([name, count]) => `- ${name}${count > 1?` (x${count})`:''}`).join('\n')

console.log(result)

feel free to ask if you need some explanation

  • Related