"Combine elements into groups and calculate their sum using the 'groupBy

Below is an example of an array:

let transactions = [{
    date: 2019,
    amount: 3000
  },
  {
    date: 2019,
    amount: 5500
  },
  {
    date: 2020,
    amount: 2300
  }
]              

I am looking to calculate the total amount for each year, resulting in the following:

{"2019": 8500, "2020": 2300}

Any suggestions on how to achieve this?

Answer №1

You can achieve this by utilizing the Array.prototype.reduce method.

let transactions = [{
    year: 2018,
    amount: 4000
  },
  {
    year: 2018,
    amount: 6000
  },
  {
    year: 2019,
    amount: 2500
  }
];

const result = transactions.reduce((accumulator, current) => {
  accumulator[current.year] ? accumulator[current.year] += current.amount : accumulator[current.year] = current.amount;
  return accumulator;
}, {});
console.log(result);

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

Animating transitions on a dynamic Bootstrap navbar using jQuery

I have the code attached here, and I successfully changed the color of the navbar and logo when scrolling down. However, I am looking to add a transition effect when this change occurs. I experimented with various transition options in CSS, but unfortunat ...

Adjust the size of the leaflet popup with Vue2Leaflet's l-popup component

I've been working on programming a web application and incorporating leaflet to showcase a map. I've set up markers and popups that show up when the markers are clicked. However, I've noticed that the popups look a bit odd right now – the ...

Tricks for displaying a dynamic object tooltip in Three.js

Can anyone help me figure out how to create a HUD hint effect for a moving object? I envision something like this: An asteroid is floating through space, and when I click on it, a hint box with information pops up. I've been playing around with thi ...

Is the required attribute malfunctioning in HTML5?

I've come across some similar inquiries, but none of them address my specific question. I am working on a form where certain details are required, while others are optional. I have used the required tag for the mandatory fields. The submit button is l ...

Leveraging the power of map in an Angular typescript file

I've been attempting to populate a Map in Angular by setting values dynamically. When certain buttons are clicked, the onClick function is invoked. typeArray: Map<number,string>; Rent(movieId: number){ this.typeArray.set(movieId,"Rental ...

Learn how to use Javascript and ASP.NET to refresh the parent page in Mozilla Firefox browser

The code window.opener.location.reload(); works well in Internet Explorer, but it doesn't refresh the parent page in Mozilla Firefox. Can someone please advise me on how to refresh the parent page in a way that is cross-browser compatible? Here is th ...

Ways to achieve 8 columns in a single row using Javascript and Bootstrap

Recently, I created a simple function for searching movies and manipulating them in the DOM. The issue arises when a movie name is entered and the API response returns around 20-30 recommendations. I wanted to display this fetched data in 8 columns per row ...

Unit testing in Angular JS is crucial, especially when testing functions in services that do not return any values

Apologies if this has been asked before, but I couldn't find a solution to my issue. I need to create tests for a service within an Angular JS application. The main function of the service returns and is used as an external method. There are also a ...

What steps can a web developer take to view user console errors?

Is there an effective method for a web developer to receive notifications of console errors logged by other authorized users? I am currently working with Express, Passport, and MongoDB. These errors may occur on either the client or server side. One approa ...

Search input in Handsontable header periodically clears when scrolling

Encountering a problem with preserving search terms in text input fields within HoT headers. After entering a search term and scrolling down, the term often gets cleared. This issue seems to be linked to the freeze behavior of HoT headers during scrolling. ...

Caution: A non-boolean attribute received a value of `false`. What is the correct way to provide a boolean value?

I'm encountering an issue with the code below: react-dom.development.js:67 Warning: Received false for a non-boolean attribute high. If you want to write it to the DOM, pass a string instead: high="false" or high={value.toString()}. Despi ...

Break big files into pieces and upload them incrementally with nodejs

I'm currently working on a project that involves uploading very large files in chunks to a server. The functionality on the server side is running smoothly, but I've encountered an issue with the client-side code. My approach so far has been to a ...

Navigating a collection of objects after a button is clicked

My current library project involves looping through an array of objects to display them on a grid based on input values. Here is the code snippet for my loop: const addBook = (ev) => { ev.preventDefault(); let myLibrary = []; let bookIn ...

Issue with filtering of values returned by functions

I've been working with Angular's currency filter and I've run into an issue. It doesn't seem to be filtering the data that is returned from a function. I have a feeling that I might be missing something, perhaps it has to do with how th ...

Is it possible to store multiple keys in HTML local storage?

Is there a way to store multiple keys to local storage without overwriting the previous ones when multiple people take a survey and refresh? Could they be grouped by userID or sorted in any way? $('form').submit(function() { $('input, ...

The animation in Rive feels sluggish when navigating to a page with animation in Blazor WASM, despite implementing dispose methods

After attempting to display river animation on the index page using Blazor WASM (basic template), I encountered some performance issues. When navigating back and forth between the Counter page and the index page, I noticed that after around 20 clicks, the ...

Can I issue multiple SADD or ZADD commands in a single .sadd/.zadd call using ioredis?

I'm currently experimenting with ioredis for caching and indexing a substantial volume of data. However, my searches haven't yet yielded information on whether it supports performing multiple SADDs in one call. Can this be done, and if so, are t ...

What is the reason Angular is unable to locate a controller for a directive in an external file?

As a newcomer to Angular, I'm struggling to comprehend John Papa's recommendations. His guidelines suggest placing controller logic inside directives, but this approach doesn't seem intuitive to me. Despite my efforts to implement it myself, ...

Struggling to Implement Insertion Sort with JSON Data

public class ReverseList extends HttpServlet { public static void sort(int arr[]) { int N = arr.length; int i, j, temp; for (i = 1; i< N; i++) { j = i; temp = arr[i]; while (j > 0 && temp &l ...

Issue encountered while trying to download Jade through npm (npm install -g jade)

I am having trouble downloading jade via npm on my Mac (Yosemite). After downloading node and updating npm, I tried to install jade but encountered a series of errors that I cannot resolve. Even attempting to use sudo did not help, as it only displayed s ...