Opus Industries
Opus Industries

Reputation: 13

How would I transform an array into a list

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.

Upvotes: 1

Views: 54

Answers (1)

R4ncid
R4ncid

Reputation: 7129

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)

Upvotes: 3

Related Questions