Group and count values in an array into an object

I have the following information in a form of Array

0: { first: "sea",      second: "deniz",   languageId: "English-Turkish"}
1: { first: "play",     second: "oynamak", languageId: "English-Turkish"}
2: { first: "swim",     second: "yuzmek",  languageId: "English-Turkish"}
3: { first: "foo",      second: "bar",     languageId: "German-Russian"}
4: { first: "computer", second: "l'ordi",  languageId: "English-French"}

I need to group them by languageId and count the items which belong to these groups. I also have the following Object for this,

export class stats{
    name: String;
    count: number;
}

At the end I need the following information;

0: { name: "English-Turkish",  count: 3 }
1: { name: "German-Russian",   count: 1 }
2: { name: "English-French",   count: 1 }

Array.reduce function looks like a good way to do that to me, but could not figure it out. How can I implement this?

Answer

Sadly, array.reduce probably isn’t the right tool for this.

But is this what you are looking for? You could turn it into a function if you needed to use it frequently.

let items = [
  { first: "sea",      second: "deniz",   languageId: "English-Turkish"},
  { first: "play",     second: "oynamak", languageId: "English-Turkish"},
  { first: "swim",     second: "yuzmek",  languageId: "English-Turkish"},
  { first: "foo",      second: "bar",     languageId: "German-Russian"},
  { first: "computer", second: "l'ordi",  languageId: "English-French"},
];
let grouped = {};
for (let item of items) {
  let { languageId } = item;
  if (!(languageId in grouped)) {
    grouped[languageId] = [];
  }
  grouped[languageId].push(item);
}
let counts = Object.entries(grouped).map(([name, arr]) => ({ name, count: arr.length }));
console.log(counts);

This has both grouped and counts, so if you needed them all grouped together; it has that too.

Leave a Reply

Your email address will not be published. Required fields are marked *