I am trying to iterate through an array with strings that uses a for loop, then a nested for loop to convert each individual character into a number, a conditional statement to leave out the '-', then add the numbers together in each individual index, to then compare the largest sum of each index and return the index with the largest sum.
var cards = ['98-23', '65-98', '43-14', '28-63'];
var sum = 0;
for (var i = 0; i < cards.length; i++) {
console.log('i // ' + i);
for (var j = 0; j < cards[i].length; j++) {
if (cards[i][j] !== '-') {
sum += parseInt(cards[i][j]);
console.log(sum);
}
}
}
output is:
i // 0
9
17
19
22
i // 1
28
33
42
50
i // 2
54
57
58
62
i // 3
64
72
78
81
I tried implementing
for( var j = 0; j <= cards[i].length; j++) {
}
but it returns;
i // 0
9
17
19
22
NaN
i // 1
5 > NaN
i // 2
5 > NaN
i // 3
5 > NaN
How would I go about adding each individual index without adding them all together?
I think you were pretty closed to the final solution so I won't be too bothered reinventing another solution for it.
Essentially what you need is a variable, in this case I have used an object
, to contain information about what is the current largest Item
and the largest item value
.
For each iteration, after you have executed the nested loop you should know how much an item weights. Then using the item value, compare it against the current largest. If it is larger than the existing largest then override its detail. Also, you increment the sum
variable with the current item's value, that way you get both informations collected.
Example:
var cards = ['98-23', '65-98', '43-14', '28-63'];
// For tracking what is the current largest and total sum
var sum = 0;
var largestItem = {
item : "",
value : 0
};
// For each item in array
for ( var i = 0; i < cards.length; i++ ) {
var itemValue = 0;
// for each character within item
for ( var j = 0; j < cards[i].length; j++ ) {
if ( cards[i][j] !== '-' ) {
itemValue += parseInt(cards[i][j]);
}
}
// Compare with current largest
if (itemValue > largestItem.value) {
largestItem.item = cards[i];
largestItem.value = itemValue;
}
// Increment sum with existing item value
sum += itemValue;
}
console.log("Sum = " + sum);
console.log("Largest item = " + largestItem.item);
console.log("Largest item value = " + largestItem.value);