JavaScript addition / sum loop - javascript

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]);

Related

Finding the sum of a "counter" variable loop that ran ten times then was pushed into the "numbers" array. Each way I tried resulted with a list

I'm asking for help to find the sum of an array with elements that were pushed from a counter variable that had previously looped 10 times. I'm new to Javascript and was practicing for an assessment, and I've tried several different ways to do it and have only resulted with just a list of the elements within the numbers array.
var counter = 10;
var numbers = [];
for (i = 1; i <= 10; i ++) {
counter = [i + 73];
numbers.push(counter);
}
console.log(numbers);
function sum(arr) {
var s = 0;
for(var i = 0; i < arr.length; i++) {
s = s += arr[i];
}
return s;
}
console.log(sum([numbers]));
function getArraySum(a) {
var total = 0;
for (var i in a) {
total += a[i];
}
return total;
}
var numbers = getArraySum([numbers]);
console.log(numbers);
you should push only the value of counter without the brackets and then make a reduce to have the sum of each number in the array
var counter = 10;
var numbers = [];
for (i = 1; i <= 10; i++) {
counter = i + 73;
numbers.push(counter);
}
console.log(numbers.reduce((a,b) => a+b));
You had a couple of typos in the code:
Typos
You were wrapping the sum in square brackets:
counter = [i + 73];
You should just remove the brackets like:
counter = i + 73;
2. You were wrapping a value that is already an array in square brackets while passing it as an argument to a function:
sum( [numbers] )
// ...
getArraySum( [numbers] );
You should remove the brackets, like this:
sum( numbers );
// ...
getArraySum( numbers );
Fix
I updated the code that you shared to fix the above-mentioned things:
var numbers = [];
// Loop 10 times and push each number to the numbers array
for (var i = 1; i <= 10; i ++) {
var sumNumbers = i + 73;
numbers.push(sumNumbers);
}
console.log(numbers);
function sum(arr) {
var total = 0;
for(var i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
// Call the function by passing it the variable numbers, holding an array
var result1 = sum(numbers);
console.log( result1 );
function getArraySum(a) {
var total = 0;
for (var i in a) {
total += a[i];
}
return total;
}
var result2 = getArraySum(numbers);
console.log(result2);

Return a piece of an array after finding the highest integer in java script?

So after working on finding the highest sum of any given amount of credit card numbers I realized I dug myself into a bit of a hole. (currently using 3 cards "123-123, 234-234 and 345-345" as test numbers.) After writing this out:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace (/-/g, "");
for (var j = 0; j < eXt.length; j++) {
sum += parseInt(eXt.substr(j, 1));
}
sumpre.push(sum);
}
console.log(sumpre);
var highest = sumpre[0];
for (var i=1; i<=sumpre.length; i++){
if (sumpre[i]>highest){
highest=sumpre[i];
}
}
console.log(highest)
Which works to find the highest sum, however; I need it to return the card number with the highest sum in its original form at the end and am not sure what method would be best to get back to that or if I should reformat it from the start.
As I mentioned in a comment, or as shown in Gerardo's answer, one way to do it with minimal changes to your current code is to use highest to keep the index of the array item with the highest value, instead of keeping the actual value itself - then you could retrieve the original card value via that index.
But for fun, here's another way to do it:
function sumDigitsInString(s) {
return Array.prototype.reduce.call(s, function(p, c) { return p + (+c || 0); }, 0);
}
function itemWithLargestSum(a) {
return a.reduce(function(p, c) {
var sum = sumDigitsInString(c);
return p[0] > sum ? p : [sum, c];
}, [0])[1];
}
// given an array of strings:
var input = ["123-123", "234-234", "345-345", "111-111"];
var largest = itemWithLargestSum(input);
console.log(largest);
Further reading:
.call() method
Array .reduce()
Unary plus operator
|| operator
?: (ternary) operator
You could also do something like this, just with Array methods.
var inputCards = ["989-000", "123-999", "456-456"];
var sum = 0,
sumNumbers = {},
maxVal = 0;
inputCards.map(function(num) {
var replaceText = new RegExp(/-/g);
var number = num.replace(replaceText, "").split("");
var prevVal = 0;
sumNumbers[num] = number.reduce((prevVal, currentVal) =>
parseInt(prevVal, 10) + parseInt(currentVal, 10));
});
console.log(Object.keys(sumNumbers).reduce((maxVal, currentVal) =>
sumNumbers[maxVal] > sumNumbers[currentVal] ? maxVal : currentVal));

JavaScript Total Returns NaN

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);

Comparing elements in an array, finding the largest sum of the elements

I am attempting to write a single function in javascript that compares credit card numbers listed strings within an array. The function should find the credit card number with the largest sum, and return that number as the original string within the input array. I am completely stuck, and cannot get past this 'undefined' error message. Here is what I have:
function highest(inputArray) {
var sum = 0;
var currentHighest = 0;
var largest = 0;
for (a = 0; a < inputArray.length; a++) {
var tempArray = inputArray[a].replace(/\D/g, '');
}
function sumDigits(str) {
sum = 0;
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i), 16);
}
return sum;
}
if (sumDigits(tempArray) >= currentHighest) {
currentHighest = sum;
largest = inputArray[a];
return largest;
} else {
return largest;
}
}
var numberArray = [];
console.log(highest(numberArray));
You have a good number of basic errors in your code. Rather than break it down, I will simply put the code revision in here.
var ipa = ['4916-2600-1804-0530', '4779-2528-0088-3972', '4252-2788-0093-7978', '4556-4242-9283-2260'];
function highest(inputArray) {
var currentHighest = 0;
var largest = 0;
var tempArray = [];
for (var a = 0; a < inputArray.length; a++) {
tempArray.push(inputArray[a].replace(/\D/g, ''));
}
function sumDigits(strA) {
var sum = 0;
for (var i = 0; i < strA.length; i++) {
sum += parseInt(strA.charAt(i), 10);
}
return sum;
}
for (var a = 0; a < tempArray.length; a++) {
var csum = sumDigits(tempArray[a]);
if (csum >= currentHighest) {
currentHighest = csum;
largest = inputArray[a];
}
}
return largest;
}
console.log(highest(ipa));
'use strict';
// initial array of numbers
let numbers = ['4916-2600-1804-0530', '4779-2528-0088-3972', '4252-2788-0093-7978', '4556-4242-9283-2260'];
// remove "-" symbol
let normilized = numbers.map(number => number.replace(/-/g, ''));
// get sum for each number
let sums = normilized.map(
number => [].reduce.call(number, (prev, value) => {
prev += +value;
return prev;
}, 0));
// find max sum
let max = Math.max.apply(null, sums);
// find position of that sum
let indexOfMax = sums.indexOf(max);
// get card number
console.log(numbers[indexOfMax]);
Based on my understanding of your question, I hope this is what you are looking for.
In addition to doing a basic loop over the array, you can also sort the array in ascending order and simply pick out the last item of the array for your largest credit card number.
Sample Fiddle here:
https://jsfiddle.net/xxo3m8zf/1/
Sample Function:
function largestSum(arr) {
arr.sort();
return largest = arr[arr.length-1];
}

Why won't my inputs value sum?

Im trying to do a sum of values i get from id but it keeps appending second value to first instead of doing sum as it should.
Example 23+25=2325
Heres my code:
This is the code im using to sum.
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = document.getElementById("veb_blocos-"+i).value;
var two = document.getElementById("veb_pellet-"+i).value;
var sum1 = one+two;
document.getElementById("total1-"+i).value = sum1;
};
});
Try this:
var one = parseInt(document.getElementById("veb_blocos-"+i).value, 10);
var two = parseInt(document.getElementById("veb_pellet-"+i).value, 10);
Because the value of an input is a string. Cast it to int.
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = document.getElementById("veb_blocos-"+i).value;
var two = document.getElementById("veb_pellet-"+i).value;
var sum1 = parseInt(one,10)+parseInt(two,10);
document.getElementById("total1-"+i).value = sum1;
};
});
Here is the safest possible solution (presuming the requested DOM nodes are present):
$('input').blur(function () {
var i = 0,
one = 0,
two = 0;
for (i = 1; i <= value; i += 1) {
one = Number(document.getElementById("veb_blocos-" + i).value);
two = Number(document.getElementById("veb_pellet-" + i).value);
if (isNaN(one)) {
one = 0;
}
if (isNaN(two)) {
two = 0;
}
document.getElementById("total1-" + i).value = one + two;
};
});
Try:
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = parseInt(document.getElementById("veb_blocos-"+i).value);
var two = parseInt(document.getElementById("veb_pellet-"+i).value);
var sum1 = one+two;
document.getElementById("total1-"+i).value = sum1;
};
});
It's because your values are string datatypes instead of a number type. You'll need to parse them first.
$('input').blur(function() {
for (var i=1; i<=value; i++) {
var one = parseFloat(document.getElementById("veb_blocos-"+i).value);
var two = parseFloat(document.getElementById("veb_pellet-"+i).value);
var sum1 = one+two;
document.getElementById("total1-"+i).value = sum1;
};
});

Categories