Reputation: 25
I am doing an exercise on JS Hero website:
Write a function add that takes a string with a summation task and returns its result as a number. A finite number of natural numbers should be added. The summation task is a string of the form '1+19+...+281'.
Example:
add('7+12+100')
should return 119.
The code I have written is as follows:
function add (string) {
let partsArray = string.split("+");
let added = parseInt(partsArray[0]);
for (let i=0; i<=partsArray.length; i++) {
added = added + parseInt(partsArray[i]);
}
return added;
}
It returns NaN. Any ideas how to solve this one?
Upvotes: 0
Views: 1069
Reputation: 1
function add(string) {
let parts = string.split("+")
let sum = parseInt(0);
for(let i=0;i<parts.length;i++){
console.log(parts[i])
sum = sum + parseInt(parts[i])
}
return sum
}
Upvotes: 0
Reputation: 1
function add(given)
{
let data=given.split('+');
let nums=data.map(function(num){
return parseInt(num)
})
let sum=0
for(let i=0;i<nums.length;i++)
{
sum=sum+nums[i];
}
console.log( sum)
}
add('7+12+100')
Upvotes: 0
Reputation: 1
The simplest possible answer is:
function add(str){
return eval(str)
}
Upvotes: 0
Reputation: 1
function add(input) {
let myinput = input.split("+") //split your value
let sum = 0;
for (let i = 0; i < myinput.length; i++) {
sum = sum + +myinput[i]; //use + for identify the number value
}
return sum;
}
Upvotes: 0
Reputation: 4674
If you still want to start with the first index ..you can do it like below
function add (string) {
let partsArray = string.split("+");
let added = parseInt(partsArray[0]);
for (let i=1; i<partsArray.length; i++) {
added += parseInt(partsArray[i]);
}
return added;
}
Upvotes: 1
Reputation: 169
You could also use the reduce method:
function add(string) {
return string.split('+').reduce((accumulator, currentValue) => accumulator +
parseInt(currentValue, 10),0)
}
Upvotes: 1
Reputation: 10572
You were going out of bounds on your array. Also you should just initialize the added to 0 as you start looking at the array from index 0. Note I added some console.logs to give you an idea of how you might debug something like this.
function add (string) {
let partsArray = string.split("+");
console.log("parts", partsArray);
let added = 0;
for (let i=0; i<partsArray.length; i++) {
console.log("i",parseInt(partsArray[i]));
added += parseInt(partsArray[i]);
}
return added;
}
If you add the <=
back and run the code with the console.logs you will see in console the following. Note with the <=
you have 4 indexes rather than the expected 3. This is because the size is 3 but the array is indexed from zero. When you use <
you get the expected answer.
Upvotes: 4