-1

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?

0

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

You might want to link to some documentation particularly to "logical nullish assignment" which isn't that well known.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.