Calculate sum with javascript

How to sum the values of a JavaScript object?

The Object.values() method returns an array of a given object’s own enumerable property values, in the same order as that provided by a for. in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

You can use this function like that:

Note that this code uses some ECMAScript features which are not supported by some older browsers (like IE). You might need to use Babel to compile your code.

This requires you pull a 60K library just to have Object.values() , which will be polyfilled with a for loop on every browser besides Firefox. Even without a polyfill, it’s 4x slower than a regular for loop for me.

@Blender You need to use Babel anyway if you want to use any of the new ECMAScript features and still support older browsers. Besides, if someone visits this question for example after 2 years, modern browsers will probably implement Object.values() until that time.

The accepted answer has a very similar approach, but the function passed to reduce seems a bit more foolproof. Did you leave out the parsing on purpose?

@Blender It seems I was right – a year and a half passed, and Object.values() is supported by all modern browsers.

You could put it all in one function:

function sum( obj ) < var sum = 0; for( var el in obj ) < if( obj.hasOwnProperty( el ) ) < sum += parseFloat( obj[el] ); >> return sum; > var sample = < a: 1 , b: 2 , c:3 >; var summed = sum( sample ); console.log( "sum: "+summed );

For fun’s sake here is another implementation using Object.keys() and Array.reduce() (browser support should not be a big issue anymore):

function sum(obj) < return Object.keys(obj).reduce((sum,key)=>sum+parseFloat(objCalculate sum with javascript||0),0); > let sample = < a: 1 , b: 2 , c:3 >; console.log(`sum:$`);

But this seems to be way slower: jsperf.com

Great job highlighting the performance difference between the solutions. Whilst the Object.keys().reduce looks so much more elegant, it is 60% slower.

If you’re using lodash you can do something like

I think JS considers the values as strings. so the answer would be like «123» instead of «6». Please correct me if I am wrong.

Now you can make use of reduce function and get the sum.

const object1 = < 'a': 1 , 'b': 2 , 'c':3 >console.log(Object.values(object1).reduce((a, b) => a + b, 0));

A regular for loop is pretty concise:

var total = 0; for (var property in object)

You might have to add in object.hasOwnProperty if you modified the prototype.

Honestly, given our «modern times» I’d go with a functional programming approach whenever possible, like so:

const sumValues = (obj) => Object.keys(obj).reduce((acc, value) => acc + obj[value], 0); 

Our accumulator acc , starting with a value of 0, is accumulating all looped values of our object. This has the added benefit of not depending on any internal or external variables; it’s a constant function so it won’t be accidentally overwritten. win for ES2015!

Читайте также:  Python приоритет логических операторов

Any reason you’re not just using a simple for. in loop?

var sample = < a: 1 , b: 2 , c:3 >; var summed = 0; for (var key in sample) < summed += sampleCalculate sum with javascript; >; 
let prices = < "apple": 100, "banana": 300, "orange": 250 >; let sum = 0; for (let price of Object.values(prices)) < sum += price; >alert(sum)

I am a bit tardy to the party, however, if you require a more robust and flexible solution then here is my contribution. If you want to sum only a specific property in a nested object/array combo, as well as perform other aggregate methods, then here is a little function I have been using on a React project:

var aggregateProperty = function(obj, property, aggregate, shallow, depth) < //return aggregated value of a specific property within an object (or array of objects..) if ((typeof obj !== 'object' && typeof obj !== 'array') || !property) < return; >obj = JSON.parse(JSON.stringify(obj)); //an ugly way of copying the data object instead of pointing to its reference (so the original data remains unaffected) const validAggregates = [ 'sum', 'min', 'max', 'count' ]; aggregate = (validAggregates.indexOf(aggregate.toLowerCase()) !== -1 ? aggregate.toLowerCase() : 'sum'); //default to sum //default to false (if true, only searches (n) levels deep ignoring deeply nested data) if (shallow === true) < shallow = 2; >else if (isNaN(shallow) || shallow < 2) < shallow = false; >if (isNaN(depth)) < depth = 1; //how far down the rabbit hole have we travelled? >var value = ((aggregate == 'min' || aggregate == 'max') ? null : 0); for (var prop in obj) < if (!obj.hasOwnProperty(prop)) < continue; >var propValue = obj[prop]; var nested = (typeof propValue === 'object' || typeof propValue === 'array'); if (nested) < //the property is an object or an array if (prop == property && aggregate == 'count') < value++; >if (shallow === false || depth < shallow) < propValue = aggregateProperty(propValue, property, aggregate, shallow, depth+1); //recursively aggregate nested objects and arrays >else < continue; //skip this property >> //aggregate the properties value based on the selected aggregation method if ((prop == property || nested) && propValue) < switch(aggregate) < case 'sum': if (!isNaN(propValue)) < value += propValue; >break; case 'min': if ((propValue < value) || !value) < value = propValue; >break; case 'max': if ((propValue > value) || !value) < value = propValue; >break; case 'count': if (propValue) < if (nested) < value += propValue; >else < value++; >> break; > > > return value; > 

It is recursive, non ES6, and it should work in most semi-modern browsers. You use it like this:

const onlineCount = aggregateProperty(this.props.contacts, 'online', 'count'); 

obj = either an object or an array
property = the property within the nested objects/arrays you wish to perform the aggregate method on
aggregate = the aggregate method (sum, min, max, or count)
shallow = can either be set to true/false or a numeric value
depth = should be left null or undefined (it is used to track the subsequent recursive callbacks)

Shallow can be used to enhance performance if you know that you will not need to search deeply nested data. For instance if you had the following array:

[ < id: 1, otherData: < . >, valueToBeTotaled: ? >, < id: 2, otherData: < . >, valueToBeTotaled: ? >, < id: 3, otherData: < . >, valueToBeTotaled: ? >, . ] 

If you wanted to avoid looping through the otherData property since the value you are going to be aggregating is not nested that deeply, you could set shallow to true.

Читайте также:  Html panel with text

Источник

How to sum numbers in Javascript

Hi i have a table in which i want in the first cell of second row «a2» to show me the total of selected number from the dropdown + the number from first row «a1». How can i do that? For now i’ve made it to show me the number chosen from the dropdown. Also how to make it sum the number digit by digit and show the total?

   table < font-family: arial, sans-serif; border-collapse: collapse; width: 100%; >td, th, tr  Number:  

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Источник

Calculate the sum of values in input elements using JavaScript

I’m trying to compute the sum of many inputs that are displayed, in order to make an invoice. All products that must be invoiced are recorder in my database, and I wrote this JavaScript function to calculate the total:

  

The problem is that I get Uncaught TypeError: Cannot read property ‘value’ of null on the line total = total + document.getElementById(«p»+(i+1)).value; I really do not understand why, because all my variables are declared.

4 Answers 4

You already got the elements by using getElementsByClassName , why you are getting it again by id? You can try following:

function getItems() < var items = document.getElementsByClassName("items"); var itemCount = items.length; var total = 0; for(var i = 0; i < itemCount; i++) < total = total + parseInt(items[i].value); >document.getElementById('tot').value = total; > getItems();​ 

One or more of the items with an id for «p»+(i+1) apparently does not exist. You didn’t show us your HTML so we can’t be more specific than that.

But, since you already have a nodeList that is an array-like list of the items from getElementsByClassName() , there is no need to get them all over again. As such, you can much more safely rewrite the code to use that and it should also protect you from trying to reference a non-existent item since getElementsByClassName() won’t return null items. There are also a couple other issues:

  1. You need to convert the results to numbers before doing the addition so you are adding numbers, not strings: total = total + Number(items[i].value);
  2. You also need to put the return AFTER you assign the total or the assignment will not get executed: document.getElementById(‘tot’).value = total; return total;
  3. And, since you don’t show us your HTML, we don’t know what items actually exist so you can protect your code from items that don’t exist by using the actual nodeList that comes back get the getElementsByClassName() call rather than retrieving items over again. All items in the nodeList that comes back from that function will exist:

With these changes and some other cleanup, the whole function would look like this:

  

Источник

Javascript Sum Values

But, instead of calculating the values of a and b, the output (c) only combine those two values. So the output given is :

Perhaps a duplicate since the code given does not produce the error: stackoverflow.com/q/14496531/4294399

8 Answers 8

Make sure the values are numbers, otherwise they will concat instead of suming.

a = parseInt(a, 10); // a is now int 

Your code is adding (concatenating) strings. Are you sure that the code you posted represents your problem? What you have written should work. Be sure in the real code you’re not saying:

var a = '2'; // or something similar 

Or if the values are parsed from somewhere, be sure to call parseInt(a, 10) on them before doing the addition, 10 being the radix.

Or as pointed out in the comments the Number function would probably suit your purposes.

yeah. i don’t use any quotes for the values. i also already converted them to int by using parseInt(a) and parseInt(b). am i doing it right ?

well it depends. parseInt(a) doesn’t change the a variable, it returns the parsed int. So you might need to a = parseInt(a) or c = parseInt(a) + parseInt(b)

I can see that specifying the radix would help for readability, but is it really necessary here? It’s probably a more than valid assumption that this app is going to be summing base 10 numbers. Edit: I guess given that he is parsing numbers there’s the chance a ‘0’ could be prepended or something. I concede the point 😛

Better to convert to number using, well ehr, Number . No need for radix — so Number(’08’) returns 8, not 0.

The author has probably put «simplified» code so we can get an idea. Had same problem, while getting input values. JS interpreted it as string. Using «Number()» solved the problem:

var sum = Number(document.getElementById("b4_f2_"+i).value) + Number(document.getElementById("b4_f3_"+i).value) + Number(document.getElementById("b4_f4_"+i).value); 
var a = 2; var b = 5; var c = a + b; // c is now 7 

The code you show will not work the way you describe. It will result in 7 .

However, when attempting to perform addition, if either or both numeric values are actually numeric strings, the other values will be cast to strings and they will be concatenated.

This is most likely to happen when attempting to read form values, reading cookies, or some other sort of HTTP header. To convert a string to a number, you need to use parseInt() [docs]. Read through the docs on it and be sure to pay attention to, and provide, the second parameter ( radix ) to ensure the casting from string to number uses the base you expect. (The lack of info on radix in other answers is the primary reason I went ahead and posted an answer even though others had already mentioned parseInt() .)

Also, FYI, Another handy function to use when dealing with unknown values and hoping to perform mathematic operations is isNaN() [docs].

Источник

Оцените статью