Are you encountering issues with using the reduce function to calculate the total sum of object properties within an array?

I am facing an issue with summing the "amount" property of objects in an array using reduce. When I tried to add them up, it kept returning undefined even though logging the values individually worked fine.

let items = [
     { id: 0, name: "Food", amount: 30000 },
     { id: 1, name: "Insurance", amount: 25000 },
     { id: 2, name: "Rent", amount: 50000 }
   ]

    let total = items.reduce((a, b) => {
       console.log(b.amount); // 30000 (first loop)
       a + b.amount; // undefined
     }, 0);
     console.log(total);

In order to fix this issue and get the expected result of summing all amounts, I need to remember to include a return statement inside the reduce function.

   let items = [
         { id: 0, name: "Food", amount: 30000 },
         { id: 1, name: "Insurance", amount: 25000 },
         { id: 2, name: "Rent", amount: 50000 }
       ]

   let total = items.reduce((a, b) => {
       console.log(b.amount); // 30000 (first loop)
       return a + b.amount; // 105000 OK
     }, 0);
     console.log(total);

Answer №1

Retrieve the sum of all amounts stored in the items array.

let items = [{
    id: 0,
    name: "Electronics",
    amount: 15000
  },
  {
    id: 1,
    name: "Clothing",
    amount: 20000
  },
  {
    id: 2,
    name: "Books",
    amount: 10000
  }
]

let total = items.reduce((acc, item) => {
  return acc + item.amount;
}, 0);
console.log(total);

Answer №2

Array.prototype.reduce operates by returning the accumulator from the function. It seems like you missed including the return keyword in your second line.

let items = [{id:0,name:"Food",amount:30000},{id:1,name:"Insurance",amount:25000},{id:2,name:"Rent",amount:50000}];

let total = items.reduce((a, b) => {
  console.log(b.amount); 
  return a + b.amount; 
}, 0);

console.log("Total:", total);

You can also utilize destructuring and the implicit return of arrow functions in this way:

let items = [{id:0,name:"Food",amount:30000},{id:1,name:"Insurance",amount:25000},{id:2,name:"Rent",amount:50000}];

let total = items.reduce((a, { amount: b }) => (console.log(b), a + b), 0);

console.log("Total:", total);

Answer №3

Make sure to utilize the return statement,

The reduce function needs to provide a value that will serve as the initial parameter for the next iteration of the function.

let expenses = [
     { id: 0, name: "Food", amount: 30000 },
     { id: 1, name: "Insurance", amount: 25000 },
     { id: 2, name: "Rent", amount: 50000 }
   ]

let totalExpense = expenses.reduce((accumulator, currentValue) => {
  return accumulator + currentValue.amount;
}, 0);
console.log(totalExpense);

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

The jQuery code continues to loop endlessly

My current script includes a fadeIn effect on a div when the user scrolls 200px from the top, along with custom circle animations. While it works, I admit it's not the most elegant solution as I had to piece together different scripts to make it funct ...

A guide on leveraging *ngFor in Angular 4 to assemble a table featuring 2 columns in every row

I have an array of objects as shown below let columns = [ {id: 1, columnName: 'Column 1'}, {id: 2, columnName: 'Column 2'}, {id: 3, columnName: 'Column 3'}, {id: 4, columnName: 'Column 4'} ]; My ...

Tips on assigning a value to a dynamically generated drop-down element

I used arrays of strings to populate drop-down menus. Is there a way to automatically set the value of each option to match the text content? el.value = opt; seems to be ineffective. var validCoursesKeys = ['opt 1','opt 2','opt ...

Retrieving the selected value from a dropdown menu before it is altered using vanilla JavaScript

I am trying to implement a feature where the previous value of a dropdown is captured when it is changed. Essentially, I need to compare the previous and current values of the dropdown and perform an action based on that information. For example, if Option ...

Open an external program

I'm currently working on a local web application and I want to be able to trigger an external application using a button click. I came across this code that works perfectly in an .html file with Internet Explorer, but when I try to implement it within ...

What is the reason for needing a page reload in Javascript or JQuery?

I'm curious why Javascript or jQuery require a page reload before applying certain effects. CSS updates in real-time, as demonstrated by the following example: This changes dynamically without needing to refresh the page @media all and (max-width:7 ...

Embed the Nest API into your HTML5 code

My mobile HTML5 application includes a script in the index.html file. Nest.js (code below) Whenever I run my application, I encounter an error stating that Firebase is not defined. This is odd because the function seems simple: --> var dataRef = new ...

What makes running the 'rimraf dist' command in a build script essential?

Why would the "rimraf dist" command be used in the build script of a package.json file? "scripts": { "build": "rimraf dist ..." }, ...

Tips for concealing an element with Vue-html-to-paper

I am working on printing pages and need to hide certain elements. Specifically, I do not want the two button signs to be displayed when I print. I am using a plugin called https://www.npmjs.com/package/vue-html-to-paper Here is my code: <div id="print ...

Drawing an image on an Ionic 4 canvas using the drawImage method, following a change

I've been working on an app that displays an image on a canvas, with the image source coming from the parent page. Everything seems to be functioning correctly, but when I try changing the imageSrc via a button click, the canvas ends up blank. Oddly ...

Altering the interaction of a dropdown element within a banner to transition seamlessly

I am attempting to create a dropdown and rise-up banner without relying on jQuery. My goal is for it to smoothly descend and rise when the triangle is pressed, as shown in the image. Currently, the triangle is styled as text (though it could also be a butt ...

Displaying the Status of a Script that is Running Asynchronously

My script takes around 5 minutes to complete and sends an email with a file attachment once finished. The entire process happens on a single PHP page without using AJAX. I want the front end to handle form submission seamlessly, processing the request in ...

The behavior of React's useState hook is causing values to be added to instead of replaced

Seeking real-time price updates every 5 seconds, I implemented a recursive setTimeout function. However, the current behavior of the price feed is as follows: Initially, the console displays: undefined and the current price Upon a price change, the consol ...

Troubleshooting routing problems with AngularJS slider widget - struggling to navigate between pages/buttons efficiently

I am brand new to AngularJS and I am attempting to get a slider to function that I found in an online example. Currently, the slider displays on the desired page (gallery.html) and the automatic image change is working fine. However, when I try to click on ...

Showing information associated with identical IDs from a database

I manage a table called workdetails with a foreign key named personid to link all work details of the same individual. The qualificationdetails table includes these Fields: Qualificationid (Primary Key, INT, Auto_increment) QualificationType (Varchar) Qu ...

Unable to refresh HTML table using Vuex data in Vue JS

I am new to working with Vue.js and particularly Nuxt. I am facing an issue with updating a table using data fetched from the backend. Even though I can see the data in the Vuex tab when the page loads, I cannot seem to populate the table with it. The func ...

Javascript in Chrome can be used to initiate and conclude profiling

Is there a way to activate the CPU Profiler in the Chrome developer window using a Javascript call? For example: chrome.cpuprofiler.start(); //perform intensive operation chrome.cpuprofiler.stop(); Currently, my only option is to manually click on "s ...

What could be the reason for the sudden failure of my jQuery + AJAX functionality?

As a novice in JavaScript/jQuery/AJAX, I have a suspicion that the issue lies in some typo that I may have overlooked. Everything was working perfectly, but when I made some edits, the hide() + show() methods stopped functioning (I tested it on both Firefo ...

Creating a custom ESLint rule that enforces restrictions on the imports of Material UI

Currently, I'm involved in a project using Next.js 14 and Material UI 5 for styling the components. I'm curious if there's an ESLint custom rule available to control the way components are imported, potentially utilizing no-restricted-import ...

Turbolinks refusing to disregard page in Ruby on Rails application

Here is the front page view file ('Welcome/index.html.erb') : https://github.com/bfbachmann/Blog/blob/master/app/views/welcome/index.html.erb Current Rails Version: 4.2.6 The main issue at hand: I am currently struggling to display my THREE.js ...