How to group javascript array values

Viewed 41

this is my data

['aaa','bbb','ccc','ddd','aaa','bbb','eee','ccc','aaa']

the output i want

[
['aaa','aaa','aaa'],
['bbb','bbb'],
['ccc','ccc'],
['ddd'],
['eee']
]

How can I achieve this result?

1 Answers

This is a pretty simple use for reduce to group an array, and Object.values to get the result you wanted.

const input = ['aaa','bbb','ccc','ddd','aaa','bbb','eee','ccc','aaa']

const output = Object.values(input.reduce( (acc,i) => {
    acc[i] ??= []
    acc[i].push(i);
    return acc;
},{}))

console.log(output);

Related