Ceri Westcott
Ceri Westcott

Reputation: 300

Group elements in an array with count

I am tasked with essentially converting an array that follows the format

['A','A','A','A','B','B','C']

I have to group them together in the format of "A(4), B(2), C(1)". I have been able achieve half of what is asked via the code here

this.dataArray.map((obj) => obj.recordType).join(', ');

Which achieves "A, B, C" but I need the count. I know this can be achieved with a for loop but I was wondering if there are any other methods of achieving this without this.

Upvotes: 0

Views: 554

Answers (1)

Passersby
Passersby

Reputation: 1172

You could use a reduce to create an object by key and then use Object.entries to loop through the keys.

const array = ['A','A','A','A','B','B','C'];

const counts = array.reduce((acc: { [key: string]: number; }, current: string) => {
   const amount = acc[current] ?? 0; // or could do || 0;
   acc[current] = amount + 1;
   return acc;
}, {}); // { A: 4, B: 2, C: 1 };



return Object.entries(counts).map(([key, value]) => {
    return `${key} (${value})`;
}).join(','); // A (4), B (2), C (1)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

Upvotes: 1

Related Questions