Techniques for finding the total value of a JSON array

After retrieving values from a database, I am using them in JSON/javascript as an array. For example, see

https://i.sstatic.net/nLzk9.png

The issue arises when trying to calculate the sum of the array elements.
I attempted to solve it with this code:

var obj1 = JSON.parse(data);
var mar = obj1.march;
var quantite = obj1.quant;
const sum = quantite.reduce((result,number)=> result+number);

console.log(sum);

Here is the output I received in the console

https://i.sstatic.net/klBh4.png

I am still learning about JSON and javascript, so any guidance or assistance would be greatly appreciated!

Answer №1

All the items in the given array are strings, hence the usage of the + operator results in their concatenation. To perform addition and avoid this issue, you should first parse them into integers like so:

const sum = quantities.reduce((result, number) => parseInt(result) + parseInt(number));

Answer №2

It appears that your dataset consists of strings rather than integers. Consider refining your reduce function:

quantite.reduce((result,number) => parseInt(result)+parseInt(number));

Answer №3

Start with the initial value in the reduce() function and ensure that number is treated as a number when performing addition

quantity.reduce((result, num) => (result + Number(number)), 0);
                                        // start value   ^^

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

Issues with Jquery Div sliding transitions from right to left are not functioning correctly

Creating page transitions in jQuery similar to "http://support.microsoft.com/." Encountering an issue where after the page transitions are completed, they start from the left instead of the expected right direction. Referencing this fiddle (Working Code) ...

Unable to establish a connection with the default port on Mongo DB while utilizing Node.js

I am new to using Node.js and I'm trying to establish a connection with MongoDB in my Node.js application, but I'm encountering issues. Here is the code snippet: var mongo = require("mongodb"); var host="127.0.0.1"; var port=mongo.Connection.DE ...

Preserve the output from the jQuery ajax request

I have created a custom function that calls an ajax request and saves the response data to a variable before returning it. It always shows '0' as the return value, but the alert displays numbers like 3712. Below is the implementation of the func ...

Can anyone provide guidance on uploading data to a mongodb database? I've attempted a few methods but keep encountering errors

const info = { name, price, quantity, image, desc, sup_name, email } fetch('https://gentle-plateau-90897.herokuapp.com/fruits', { method: 'POST', headers: { 'content-type': 'application/jso ...

The error message "firebase.initializeApp is not defined" indicates that the object is not properly initialized

Every time I try to open the debugger in Safari, I encounter an error indicating that 'undefined' is not recognized as an object when evaluating 'firebase.initializeApp'. The error specifically points to the line of code: firebase.initi ...

How to stop a checkbox from being selected in Angular 2

I have a table with checkboxes in each row. The table header contains a Check All checkbox that can toggle all the checkboxes in the table rows. I want to implement a feature where, if the number of checkboxes exceeds a certain limit, an error message is ...

Colorful D3.js heatmap display

Hello, I am currently working on incorporating a color scale into my heat map using the d3.schemeRdYlBu color scheme. However, I am facing challenges in getting it to work properly as it only displays black at the moment. While I have also implemented a ...

Error: undefined property causing inability to convert to lowercase

I am encountering an error that seems to be stemming from the jQuery framework. When I attempt to load a select list on document ready, I keep getting this error without being able to identify the root cause. Interestingly, it works perfectly fine for the ...

The surprising behavior of Rails rendering partials even when they are commented out has

I'm intrigued by how Rails 5 handles partials and if there might be a hidden problem I haven't encountered yet. On my current page, I have two partials - one that is included in the HTML itself, and another that is supposed to render inside an aj ...

My JavaScript array is not working with the stringify function

I am trying to encode my JavaScript array into JSON using stringify. Here is the code: params["margin_left"] = "fd"; params["text"] = "df"; params["margin_to_delete"] = "df"; console.info(params); When I check the output in Chrome console, it shows: [m ...

Creating a Vue component using v-for and a factory function allows for dynamic

I am currently developing a Table component using factory functions for all logic implementation. Within a v-for loop, I generate a cell for each item in every row. The factory Below are the actual factories that I import into the respective vue page whe ...

Is there a method in Discord.JS to remove an embed from a message sent by a user?

Currently, I am developing a bot utilizing the Discord.JS API. This bot is designed to stream audio from specific YouTube links using ytdl-core. Whenever a link is typed in, an embed of the YouTube video appears. While there are methods to disable embeds o ...

Modifying HTML text with JavaScript according to the content of the currently selected div

Greetings! This is my first time posting a question, and I wanted to mention that I am relatively new to javascript/jquery. I have a gallery that displays image details on hover through text, while clicking on the image triggers a javascript function that ...

Unreliable static URLs with Next.js static site generation

I've recently built a Next.js website with the following structure: - pages - articles - [slug].js - index.js - components - nav.js Within nav.js, I have set up routing for all links using next/link, including in pages/articles/[slug].j ...

JSON arrays that are nested within one another

I am currently working on parsing some JSON data that contains nested arrays, and I'm facing difficulties extracting the data from the inner arrays within the main array. This is a snippet of how my JSON data is structured: {"TrackingInformationResp ...

Extract data from SOAP XML response sent by SOAP Client using PHP

After successfully making a SOAP call to an external webservice using PHP, I am now facing the challenge of parsing the response received from the SOAP service. When I use the following code: echo '{"reference": "'.$client->__getLastResponse ...

Ways to transform the DropBox chooser button into an image

I'm looking to incorporate an image in place of Dropbox's default chooser button. Despite reviewing their API documentation, I haven't come across any methods to use alternative elements for the Dropbox chooser. Does anyone have a solution f ...

Error arises during JSON parsing if the data content contains the `%` symbol

I'm struggling to solve an issue on my website related to a function that downloads articles dynamically. The problem arises when the article contains a % sign, causing a parse error. Can anyone assist me in modifying this function to handle the % sig ...

Encountered an error with Winston and Elasticsearch integration: "TypeError: Elasticsearch is not a constructor

I recently implemented winston-elasticsearch on my express server by following the code provided in the documentation var winston = require('winston'); var Elasticsearch = require('winston-elasticsearch'); var esTransportOpts = { le ...

Tips for choosing a loaded element using the jQuery load() method

I am currently facing a challenge with the following (here is a snippet of code to illustrate): <div id="container"></div> <script type="text/javascript"> $('#container').load('content.html'); $('.eleme ...