Calculate the sum of object values in JavaScript when all other values in the object are identical

Recently, I've been delving into JS high array methods and encountered an array of objects featuring cost categories and values:

[{category: "Bars", amount: 31231},
{category: "Transport", amount: 1297},
{category: "Utilities", amount: 12300},
{category: "Bars", amount: 2000},
{category: "Transport", amount: 2500},
{category: "Education", amount: 21321}]

My aim is to condense this array by summing the 'amount' values as follows:

[{category: "Bars", amount: 33231},  //31231+2000
{category: "Transport", amount: 3797}, //1297+2500
{category: "Utilities", amount: 12300},
{category: "Education", amount: 21321}]

I attempted using reduce() and forEach(), but have not yet found a solution to resolve the issue. Appreciate any guidance!

Answer №1

To achieve this, utilize the `reduce` method which allows you to iterate over the array items. For each item, check if the category does not exist in the `newObject`. If it doesn't, initialize it with a value of 0 and then add up the amounts.

var objects = [{category: "Bars", amount: 31231},
{category: "Transport", amount: 1297},
{category: "Utilities", amount: 12300},
{category: "Bars", amount: 2000},
{category: "Transport", amount: 2500},
{category: "Education", amount: 21321}];

var newObjectsMerged = objects.reduce((object, item) => {
  var category = item.category;
  var amount = item.amount;
  if (!object.hasOwnProperty(category)) {
    object[category] = 0;
  }
  
  object[category] += amount;
  return object;
}, {});

console.log("newObjectsMerged", newObjectsMerged);

Answer №2

To simplify the array, you can utilize finc to manipulate the object and either update it or add a new array to the final result.

var exampleArray = [{ category: "Bars", amount: 31231 }, { category: "Transport", amount: 1297 }, { category: "Utilities", amount: 12300 }, { category: "Bars", amount: 2000 }, { category: "Transport", amount: 2500 }, { category: "Education", amount: 21321 }],
    result = exampleArray.reduce((r, { category, amount }) => {
        var temp = r.find(o => o.category === category);
        if (temp) {
            temp.amount += amount;
        } else {
            r.push({ category, amount });
        }
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

let expenses = [{category: "Food", amount: 500},
{category: "Transportation", amount: 100},
{category: "Utilities", amount: 200},
{category: "Food", amount: 150},
{category: "Transportation", amount: 75},
{category: "Entertainment", amount: 300}];


let totalExpensesByCategory = expenses.reduce(function (accumulator, expense) {
  
  let summarizedExpense = accumulator.get(expense.category);
  if (!summarizedExpense) {
    summarizedExpense = expense;
  } else {
    summarizedExpense.amount += expense.amount;
  }
  
  accumulator.set(expense.category, summarizedExpense);
  
  return accumulator;
}, new Map());

console.log(Array.from(totalExpensesByCategory.values()))

Answer №4

Give this a shot:

let expenses = [{category: "Groceries", amount: 200},
{category: "Transportation", amount: 50},
{category: "Utilities", amount: 120},
{category: "Groceries", amount: 100},
{category: "Entertainment", amount: 75}];

// extract unique categories
let categories = [...new Set(expenses.map(item => item.category))];

// calculate total expenses for each category
let result = categories.map(category => {
    return {
        category: category,
        totalAmount: expenses.filter(item => item.category === category).reduce((acc, curr) => acc + curr.amount, 0)
    };
});

Answer №5

An ES6 solution using Array.prototype.reduce and Object.keys:

const data = [{category: "Bars", amount: 31231},{category: "Transport", amount: 1297},{category: "Utilities", amount: 12300},{category: "Bars", amount: 2000},{category: "Transport", amount: 2500},{category: "Education", amount: 21321}];

const grouped = data.reduce((all, {category: c, amount: a}) =>
    ({...all, [c]: (all[c] || 0) + a }), {});

const result = Object.keys(grouped).map(k => ({category: k,amount: grouped[k] }));

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

Struggling with textpath SVG elements in jQuery

Currently, I am implementing SVG in my project and aiming to apply the toggleClass function using jQuery on the textpath elements upon clicking. My initial plan was: $("text#names > textpath").click(function() { $(this).toggleClass("newClass"); }) ...

Challenges with using the $.remove() function in jQuery

In simple terms... I am dealing with an element called clone. It's a div with various other tags nested within it. There is also a .x contained within it. My goal is to remove the .x and then append this modified element to another element. Unfortu ...

What is the best way to create a "check all" feature in React using child components?

I have come across a few questions here that somewhat address the issue, select all managed state of controlled checkboxes but none of them provide a solution for rendering a component with a checkbox. What I want is something like this, render: funct ...

Having issues with the functionality of the jQuery HTML function

I'm working on this jQuery code snippet: $('#wrapper').html('<img src="/loading.gif">'); var formdata = $("#validateuserform").serialize(); $.post("/userformdata.php",formdata,function(html){ if(html) ...

Updating an AngularJS nested template dynamically during execution

Currently, I am facing an issue where I have a template nested within another template, and I want to load it dynamically when a specific button is clicked. Here is what I have attempted so far: This is the main body.html (which loads when a URL is provid ...

What could be causing a functional component's child component to be using stale props?

I am currently working with Next JS, but the process is similar. I have refined the code and eliminated irrelevant parts. My goal is to create a form where new fields (child components) can be added dynamically. The default setting will be 1 field, with a ...

Error: The function Task.find is not recognized in Node.js

I've been encountering an issue with my model while connected to MongoDB and having a running server. The problem seems to be related to routing through the TaskController, but I'm not sure if it's due to the model or the find() function. I ...

The array of type __NSArrayM was modified during enumeration

Application Specific Information: *** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x17204b070> was mutated while being enumerated.' ...

What is the best way to generate multiple versions of an array containing a specific number of elements and a specified size?

I'm wondering how to generate a list of all possible variations of an array with a specified size and a specified number of the same element. For example, if we have an array of size 5 with three of the same element, here are the different ways it co ...

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 ...

Tips for converting characters in an array to a Caesar cipher

I tried setting up an array that correlates capital letters with their corresponding Caesar cipher letters, so for example, A would shift 13 places to become N. I attempted to write a code that could generate this transformation, but I seem to have made an ...

Prevent certain dates from being selected in a designated input field

I am facing an issue with disabling certain array dates for a specific input field in a datepicker calendar. Even though I have included the script to exclude those dates, they are not getting disabled for that particular input field. html <input cla ...

JavaScript checking the current page's URL is crucial for maintaining accurate and dynamic

I've attempted to verify the URL using this specific function. It functions properly with single text, but fails when a URL is inputted. jQuery(document).ready ( function () { //var regExp = /franky/g; //It works fine ...

Transform collapsible color upon materialize click

Is there a way to change the color of the collapsible header only when clicked? I'm struggling with adding the color inside the class element while calling the "connect" function. Can this be achieved? <div class="collapsible-header" onclick="conn ...

Breaking apart a pipe-separated text and sending it through a JavaScript function

CSS: <div class="pageEdit" value="Update|1234567|CLOTHES=5678~-9876543?|5678"> <a href="https://host:controller">Update</a> </div> Trying to retrieve the data within the div and pass it into a JavaScr ...

Encountering a null value in a function parameter assigned within an AJAX success callback in JavaScript

function fetchData(url) { var response = null; $.ajax({ type: "GET", url: url, crossDomain: true, async: false, contentType: "application/json; charset=utf-8", da ...

Dynamic class name changes in Angular.js based on JSON object

I am trying to dynamically change the class of an <li> element based on the category value I am getting, but for some reason the class name won't update. Here is the code snippet: <div id="content"> <ul id="container" ng-controller ...

Is there a way to access comprehensive data pertaining to an ID through Ajax?

I need help with an Ajax call. Below is the code I currently have: $.ajax({ async: true, url: 'test/', type: 'POST', datatype: 'text json', data: { id: id, }, success: function(data) { // Retrieve the da ...

Issue: setAllcategories function not found

Currently engaged in using Next.js and Sanity as a Headless CMS for the backend. In the code snippet below, I have created a Categories.js file in the components folder to fetch some data. My objective is to extract all the titles from the category Array. ...

What is the method for retrieving values from an array in Objective-C?

The phone number values are listed below: ( ( 9834677334 ), ( 9977655456 ), ( 9976367777 ), ( 9654567877 ), ( 9834777347 ), ( 9994157837 ), ( 9978855544 ), ( 9873667378 ) ) Sample code snipp ...