Aggregate the values in an array and organize them into an object based on their frequency

I have an array of information structured like this:

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"}

My goal is to group them by languageId and count the items in each group. To help with this, I have an object defined as follows:

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

The desired output should be:

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

I think using the Array.reduce function would be a good approach for this task, but I'm struggling to implement it. Can you provide guidance on how to achieve this?

Answer №1

It seems like utilizing the Array.reduce function could be a viable solution, but I'm struggling to implement it successfully. Can anyone provide guidance on how to achieve this?

If you refer to .reduce(), you can streamline your code and retrieve the desired outcome in a more elegant manner as shown below:

const 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"},
];

const result = items.reduce((acc, {languageId}) => 
{
  acc[languageId] = acc[languageId] || {name: languageId, count: 0};
  // The more elegant way: acc[languageId] ??= {name: languageId, count: 0};
  acc[languageId]['count'] += 1;
  
  return acc;
}, {});

console.log(Object.values(result));

The core functionality of the reduce() method involves executing a reducer function on each element within the array to produce a single output value.

Answer №2

Unfortunately, utilizing array.reduce might not be the most suitable approach in this scenario.

However, could this be the solution you are seeking? If required frequently, you could transform it into a function.

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 includes both grouped and counts, so if you require them all grouped in one place, this option offers that functionality as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigational highlighting of current page section on a one-page website

I'm struggling with adding a navigation bar feature that will highlight the current section being viewed on my website. All I want is for the currently viewed section to appear bold in the navigation bar. Check out the codepen link: HTML <na ...

What could be causing my CORS fetch request to not send cookies to the server?

Trying to work out a CORS request using the fetch method: fetch('https://foobar.com/auth', { method: 'GET', mode: 'cors', credentials: 'include', }) The server-side code in express for impl ...

When I attempt to conceal the filter within mat-table using *ngIf, I encounter an issue where I am unable to read the property 'value' due to it being

After creating a mat-table, I encountered an issue when trying to show and hide my input filter area using a button. If I use *ngIf="showInputFilter" to hide the filter area, I receive the error message Cannot read property 'value' of u ...

Do the Push Notification APIs in Chrome and Firefox OS follow the same set of guidelines and standards?

Do Chrome and Firefox OS both use Push Notifications APIs that adhere to the same standard? If not, is either one moving towards standardization? ...

Is there a way to create tabs in JavaScript without having to edit the <head> section?

I am in need of JavaScript for creating tabs without the necessity of editing the <head> (as it is not possible). My requirement involves having three links and three divs. Whenever a link is clicked, one specific div should be displayed while the o ...

Unnecessary socket.io connection in a React component

Incorporating socket.io-client into my react component has been a learning experience. Most tutorials recommend setting it up like this: import openSocket from 'socket.io-client'; const socket = openSocket('http://localhost:8000'); In ...

Is there a way to ensure that this ajax code functions seamlessly with all types of HTML files?

Currently, I am facing a challenge with an ajax call that retrieves data from a database, which I need to load into an HTML file. The issue lies in the fact that I have various HTML files and I am unaware of their contents. Despite spending countless hour ...

Creating dependent dropdowns using Laravel Inertia Vue: A step-by-step guide

In my AddressController, I have a function called loadCity along with other CRUD functions: public function loadCities(Request $request) { $provinceId = $request->province_id; $cities = Province::where('province_id' ...

Displaying a subset of categories based on the user's selection

I have been trying to find a solution to automatically display a subcategory select drop-down only when a user selects a category. If no category is selected, the subcategory drop-down should remain hidden. I have searched online tutorials and videos for ...

Using Javascript with the Google Calendar API: How can I swiftly make a new event with the Quick Add feature?

Currently, I am exploring the Google Calendar API and struggling with implementing a Quick Add Event using javascript. Is it possible to achieve this task? Are there any resources or examples that can help me understand how to do it? My issue lies in the ...

Selecting objects within a small three.js view

I am able to showcase an entire page filled with graphical elements using three.js and can even select objects by clicking on them. However, when attempting to display three.js graphics in a small viewport within an HTML page, issues arise. In order to ca ...

Neglecting specific packages in package-lock.json

Currently facing a perplexing dilemma with no clear solution in sight. In our ongoing project, we rely on npm for package management. Although we haven't been utilizing package-lock.json file lately, the need to reintroduce it has emerged. The issue ...

Angular 4 not throwing errors when using Array.Filter and find

Having trouble filtering a list using Array.find and filter functions. Here is the function in question: setSupplierDetails(supplierId) { const supplier = this.suppliers.filter(tempSupplier => tempSupplier.id === supplierId)[0]; this.supplierName = ...

In need of guidance on displaying real-time console output in a window using Handlebars

Utilizing Handlebars, express, and node.js; I have a shell script set to execute upon completion of an HTML form submission. This script, running on the server, neatly logs its progress using console.log: builder.stdout.on('data', function(data) ...

Choosing options using an enum in Angular 2

In my TypeScript code, I have defined an enum called CountryCodeEnum which contains the values for France and Belgium. export enum CountryCodeEnum { France = 1, Belgium = 2 } Now, I need to create a dropdown menu in my form using this enum. Each ...

Manipulating front matter metadata when reading/writing a markdown file in Node.js

I have a large collection of markdown files that I need to update by adding new data to their front matter metadata. Currently, the file structure looks like this: --- title: My title here --- Markdown content here My goal is to include an id property ...

Webpack attempting to load build.js from a nested folder

I am in the process of setting up a Vue app with Vuetify and Vue Router. Everything works fine when I load the base URL "/", and I can easily navigate to /manage/products. However, if I try to directly access /manage/products by typing it into the address ...

Session management functions properly in Postman, however, encountering issues when attempting to use it on a web

Working on a NodeJS project using express-session to handle sessions. When sending a post request to http://localhost:5500/login, a session is created with an additional property userid. Upon making a get request to http://localhost:5500/ using Postman, th ...

I'm facing some difficulties in sourcing my header into a component and encountering errors. Can anyone advise me on how to properly outsource my header?

Looking to streamline my headers in my Ionic 4 project by creating a separate reusable component for them. Here's how I set up my dashboard page with the header component: <ion-header> <app-header title="Dashboard"></app-he ...

The hyperlink tag within the overlay div is unresponsive

I'm facing an issue with my overlay div (rb-overlay) that pops up when users click on a page option. The overlay takes up the entire page and includes a close button in the top right corner. However, I've noticed that the link at the end of the t ...