I am trying to sum an array of objects using JavaScript, but instead of displaying the expected outcome of 86 it displays NaN.
Note: I am not able to edit the array of objects!
var objects = [{"ID":"--"},{"ID":"58"},{"ID":"28"}];
var sum = 0;
id = objects;
for (var i = 0; i < id.length; i++) {
sum += +id[i].ID;
}
document.getElementById('here').innerHTML = "<b>Total:</b>" + sum;
objects.forEach(function(key) {
var a = document.createElement("p");
a.innerHTML = key.ID;
document.getElementById('here').appendChild(a);
});
<div id="here"></div>
JsFiddle: https://jsfiddle.net/ru266x7m/
Please be aware that this is not a duplicate of Object returning NaN when sum values as I already have the line of code var sum = 0;
You could insert a check if the value isFinite.
if (isFinite(id[i].ID)) {
sum += +id[i].ID;
}
var objects = [{"ID":"--"},{"ID":"58"},{"ID":"28"}];
var sum = 0;
id = objects;
for (var i = 0; i < id.length; i++) {
if (isFinite(id[i].ID)) {
sum += +id[i].ID;
}
}
document.getElementById('here').innerHTML = "<b>Total: </b>" + sum;
objects.forEach(function(key) {
var a = document.createElement("p");
a.innerHTML = key.ID;
document.getElementById('here').appendChild(a);
});
<div id="here"></div>
your very first data point is {"ID":"--"}
you can't add -- and get an integer from it.
"--" + 1 is NaN
if you want this to return an actual number, you must add actual numbers
update
if you need to check the values, use parseInt and isNaN inside of your loop
var value = parseInt(id[i].ID. 10);
var valid = isNaN(value);
if (valid){
sum += value;
}
An optimized version using Number constructor, isNan function and documentFragment(making only one loop instead of two):
var objects = [{"ID":"--"},{"ID":"58"},{"ID":"28"}];
var sum = 0, hereEl = document.getElementById('here'),
f = document.createDocumentFragment();
objects.forEach(function(key) {
var p = document.createElement("p"), num = Number(key.ID);
p.innerHTML = key.ID;
sum += !isNaN(num)? num : 0;
f.appendChild(p);
});
hereEl.innerHTML = "<b>Total:</b>" + sum;
hereEl.appendChild(f);
<div id="here"></div>
You can check validity of any value with isNaN type check (means is Not a Number). Type checker will return false if ID is number or string number.
var objects = [{"ID":"--"},{"ID":"58"},{"ID":"28"}];
var sum = objects.reduce((s, o) => console.log(o.ID) || s + (isNaN(o.ID) ? 0 : +o.ID), 0);
console.log('Total: ' + sum);
Related
I have an array created with a for loop that has 50 values.
var array = [];
array [0] = {
selection : 0
}
var number = 1;
for (i = 0; i < 50; i++){
array[i].selection = number;
number ++;}
How to change the value for the array[i-20].selection? I don't want to use array[30].selection
It usually works if use array[i-1].selection or array[i+1].selection but doesn't work if use anything greater than one.
Thanks
You wanted Array of Objects and not Array with single Object, right ?
var array = [];
var number = 1;
fillFrom(3, 1); // should push instead of setting and start from zero but ;-)
var res = '<table width=1><tr><td>' + JSON.stringify(array).replace(/,/g, ',<br>') + '</td>';
fillFrom(0, -49);
res += '<td>' + JSON.stringify(array).replace(/,/g, ',<br>') + '</td></tr></table>';
document.body.innerHTML = res;
function fillFrom(start, number) {
for (i = start; i < 50; i++) {
if (array[i] === undefined) array[i] = {
selection: number
};
else array[i].selection = number;
number++;
}
}
I have a function that returns the sum of all its digits For both POSITIVE and NEGATIVE numbers.
I used split method and converted it to string first and then used reduce to add them all. If the number is negative, the first digit should count as negative.
function sumDigits(num) {
var output = [],
sNum = num.toString();
for (var i = 0; i < sNum.length; i++) {
output.push(sNum[i]);
}
return output.reduce(function(total, item){
return Number(total) + Number(item);
});
}
var output = sumDigits(1148);
console.log(output); // --> MUST RETURN 14
var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4
Instead of returning the sum, it returned 4592 -1264
Am I doing it right or do I need to use split function? Or is there any better way to do this?
Sorry newbie here.
I think you'll have to treat it as a string and check iterate over the string checking for a '-' and when you find one grab two characters and convert to an integer to push onto the array. Then loop over the array and sum them. Of course you could do that as you go and not bother pushing them on the array at all.
function sumDigits(num) {
num = num + '';
var output = [];
var tempNum;
var sum = 0;
for (var i = 0; i < num.length; i++) {
if (num[i] === '-') {
tempNum = num[i] + num[i + 1];
i++;
} else {
tempNum = num[i];
}
output.push(parseInt(tempNum, 10));
}
for (var j = 0; j < output.length; j++) {
sum = sum + output[j];
}
return sum;
}
var output = sumDigits(1148);
console.log(output); // --> MUST RETURN 14
var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4
Can someone explain what I am doing wrong in this problem? I want to add the sum of the num variable using toString and Number methods. I first turn num into the string num = '12345'. Then I loop through string, turn it into a number and add it to the sum.
var num = 12345;
function sumDigits(num) {
var sumOfDigits = 0;
num.toString();
for(var i = 0; i < num.length; i++){
sumOfDigits += Number(num[i]);
}
return sumOfDigits;
}
You're not assigning the result of num.toString() to anything.
var num = 12345;
function sumDigits(num) {
var sumOfDigits = 0;
num = num.toString();
for (var i = 0; i < num.length; i++) {
sumOfDigits += Number(num[i]);
}
return sumOfDigits;
}
console.log(sumDigits(num));
I believe you can use this one :
var num = 12345;
function sumDigits(num) {
//empty variable
var str;
//check type of the incoming value
(typeof num == "string") ? str = num : str = num.toString();
//this is the same with above if you don't know how to use short handed if else
/*
if(typeof num == "string"){
str = num;
} else {
str = num.toString();
}
*/
//Array's split Method and a variable which u have create already
var arr = str.split(''), sumOfDigits = 0;
for(var i in arr){
//You should use parseInt() method.
sumOfDigits += parseInt(arr[i]);
}
//return the sum of the digits
return sumOfDigits;
};
console.log(sumDigits(num));
If you have future problems please first search a bit then write here :)
Updated:
You can use split, map and reduce to split the array, map it to integers, then use a reduce function to sum the integers.
You could eliminate the map if you want to move parse into the reduce, but I like to keep the steps separate.
var num = 12345;
function sumDigits(num) {
var sumOfDigits = num
.toString()
.split('')
.map(function(n) { return parseInt(n);})
.reduce(function(acc, val) {
return acc + val;
},
0
);
return sumOfDigits;
}
var sum = sumDigits(num);
console.log(sum)
I am trying to sum an array where array length will be provided by user. I have done it but execution time is high then required. What is an efficient way to do it. my code
function summation(){
var p = prompt("Number Only","");
var arr = [] ;
var sum = 0 ;
for (var i = 0; i < p; i++) {
arr.push(parseInt(prompt("Number Only","")));
};
for (var i = 0; i <arr.length; i++) {
sum += arr[i];
};
document.write(sum);
}
(function(){
summation();
})();
Why to use an array when you don't need an array?
function summation(){
var p = prompt("Number Only","");
var sum=0;
for(var i=0;i<p;i++){
sum+=parseInt(prompt("Number Only", ""));
}
document.write(sum);
}
This solution features an infinite loop with break, a prompt with control, a continuing input and a type checking for numbers.
The first imput for the array size is not more necessary, because of the possibillity of immediately ending with cancel or empty input.
function summation() {
var arr = [],
sum = 0,
v;
while (true) {
v = prompt("Number Only (Press [Cancel] for end input)", "");
if (!v) {
break;
}
v = parseInt(v, 10);
if (isFinite(v)) {
arr.push(v);
sum += v;
}
}
document.write('Array: ' + arr + '<br>');
document.write('Sum: ' + sum + '<br>');
}
summation();
I'm trying to add the following but it keeps concatenating and returning a string.
var nums = [1.99, 5.11, 2.99];
var total = 0;
nums.forEach(function(i) {
total += parseFloat(i).toFixed(2);
});
Yes, I need it to return / add it with the decimals. Unsure what to do
If you wanted a more functional approach, you could also use Array.reduce:
var nums = [1.99, 5.11, 2.99];
var sum = nums.reduce(function(prev, cur) {
return prev + cur;
}, 0);
The last parameter 0, is an optional starting value.
If you aren't storing strings of floats, you don't need to use parseFloat(i), that parses a float from a string. You could rewrite this as:
var nums = [1.99, 5.11, 2.99];
var total = 0;
nums.forEach(function(i) {
total += i;
});
var fixed = total.toFixed(2);
console.log(fixed);
or
var nums = [1.99, 5.11, 2.99];
var total = 0;
for(var i = 0; i < nums.length; i++){
total += nums[i];
}
var fixed = total.toFixed(2);
console.log(fixed);
var nums = [1.99, 5.11, 2.99];
var total = 0;
nums.forEach(function(i) {
total += parseFloat(i);
});
alert(total.toFixed(2));
Yes, it with the decimals
Try reduce, a recursive option:
function sum(inputNums) {
var nums = inputNums;
var total = nums.reduce(function(previousValue, currentValue, index, array) {
return previousValue + currentValue;
});
alert('' + total);
}
sum([1.99, 5.11, 2.99]);