Calculate the sum of elements with JavaScript

I am working with an array where each element is an object that also contains an array. My goal is to calculate the sum of all items in the nested arrays.

Here is the approach I have attempted:

function getSum(total, item) {
    return total + item;
}

var sum = array.reduce((total, item) => total + item.data.reduce(getSum));

However, instead of getting the sum, I am seeing a string that starts with Object...

Answer №1

To avoid getting an unexpected string, it is essential to specify an initial value for the variable total:

var sum = array.reduce((total, item) => total + item.data.reduce(getSum, 0), 0);

If you omit setting an initial value, the variable will be initialized with the first item in the array, which could lead to unexpected results, especially if the first item is an object.

You can optimize your code by utilizing total as the initial value for the second reduction process:

var sum = array.reduce((total, item) => item.data.reduce(getSum, total), 0);

Answer №2

It's quite simple

let array = [
    {values: [1,2,3]},
    {values: [4,5,6]}
];
array.reduce((result, item) => result + item.values.reduce((x, y) => x + y), 0);
// the result is 21

The second reduce function does not specify an initial value, which means that during the iterations:

  • First: x = values[0], y = values[1]
  • Second: x = running total, y = values[2]

Refer to the reduce documentation for more details

On the other hand, the first reduce function requires an initial value because the elements in its callback are not simple numbers

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

Exploring X3DOM nodes using d3.js

I'm attempting to loop through X3DOM nodes in D3.js, but I'm encountering an issue. Check out the code snippet below: var disktransform = scene.selectAll('.disktransform'); var shape = disktransform .datum(slices ...

Transforming JSON dates to Javascript dates using AngularJS and ASP.NET

How can I convert a JSON date /Date(1454351400000)/ into a proper date format using AngularJS and ASP.NET? $http.get('/home/GetProducts') .success(function (result) { $scope.products = result; }) .error(function (data) { ...

"Enhancing Collaboration with NextJs Multi-Zones' Unified Header

Currently, I have two applications named admin-shell and delivery-management, both of which are being managed using Multi Zones in NextJs. These applications share a common header with navigation links, but I am encountering difficulties navigating betwee ...

Tips for Integrating a Facebook Shop Page into Your Website

Can a Facebook shop page be integrated into a website? Any guidance on how to accomplish this task would be greatly valued. ...

Deleting a button from a list item or array in Angular 12

Having some trouble removing a list item with the click button, I've tried a few options but nothing seems to be working. Can anyone offer assistance? I need to remove a list item from my users array when clicked. Below is the Typescript code and cor ...

The information within the ajax request remains static

I made changes to my ajax data, saved it and even double-checked the file location. However, the old version is still appearing as if it's cached. Here is the original code: function setMessages(roomId, username, message){ $.ajax({ type: ...

What is the process for determining the total of elements within an array?

Imagine you have the following array: const items = [ { "amount1": "100", "amount2": "50", "name": "ruud" }, { "amount1": "40", "amount2": "60", "name": "ted" } ] Your goal is to calculate the sum of all amount1 and amount ...

The type is lacking the following properties in array.push

Encountering an issue with the register page in my IONIC app. Currently, I am utilizing a data.json file to store all user data, and I aim to create a new member with minimal information required (name, email, password) while leaving other fields empty fo ...

A guide to retrieving data in React with useSWR whenever the state changes

In a specific scenario, I need to be able to choose users from a dropdown menu. Once a user is selected, the app should display that user's data. Upon loading the page, the app fetches the data for the first user in the array allUsers?.[0]: const [us ...

How can I handle a situation in Angular where there are multiple $http requests that are interdependent and need to

Let's talk about two different URL endpoints called "fruitInfo" and "fruitDetails" The goal is to create an object with the following structure: var fruitInfoDetails = {"fruitInfo": <contents of fruitInfo response data>, "fruitDetails": <co ...

Unable to add items to the global JavaScript array variable

My goal is to populate a global array variable within my ready function, but when I attempt to access the data later on, the array appears to be empty. This is how my ready function looks: var counter = 0; var services = []; var names = [] va ...

React Router is not compatible with ReactJS app version 18

After using the command npx create-react-app, I've just set up a new ReactJS app which I think is running on React version 18 (feel free to correct me if I'm mistaken). Now, as I attempt to implement a router for this app, I find myself hesitati ...

Expanding parent nodes in Jstree to load child nodes dynamically (json)

I am trying to optimize the performance by loading the child nodes of a parent node only after clicking on that specific parent node. It is important because there are many child nodes, so this method helps in keeping the performance high. Currently, I ha ...

Exploring The Depths of HOC with Enzyme and TypeScript

I have a higher-order component (HOC) that I need to test. During shallow mounting, I need to call some class methods: it('Should not call dispatch', () => { const dispatch = jest.fn() const WrappedComponent = someHoc(DummyComp ...

Unlocking the API endpoints within nested arrays in a React project

{ [ "quicktype_id": 1, "quicktype": "Laptops", "qucik_details": [ { "type_name": "car", "type_img": "car_img" }, { "type_name": "van", "type_img": ...

Converting a string array to an integer array using the Integer.parseInt() method is not a feasible

After receiving a response from an HTTP server in the form of a string with values separated by commas, I attempted to convert it to integers at the client side using comma as a delimiter. However, I encountered issues with converting using Integer.parseIn ...

Enhance your Java sorting capabilities with Multi-Level Comparator

I'm currently faced with a task that involves sorting "Song-artist pairs" from an input file alphabetically. The sorting guidelines are as follows: Song-artist pairs should be sorted by the author's name first. If there are multiple songs by th ...

The active link for pagination in CodeIgniter is malfunctioning

Even though there might be similar posts on StackOverflow, my situation is unique. Hence, I have decided to ask this question with a specific title. Let me break down my issue into smaller parts: Part - 1: I have a regular view page where I can select a ...

Node.js tutorial: Building routes with regex and implementing redirects

Can anyone provide guidance on how to utilize route and redirect URLs with parameters in Node.js using Express? If the URL is xyz/?s=test, it should redirect to indexRouter. If the URL is xyz/, it should also redirect to indexRouter. I'm facing issu ...

Decipher complex JSON structures

I am working with a multi-level JSON structure: { "1":{ "name":"PHP", "slug":"/tag/php", "type":"Tag" }, "2":{ "name":"JavaScript", "slug":"/tag/javascript", "type":"Tag" }, "3":{ ...