-1

I was asked in an interview to add numbers in an array without using loop.

I solved it using recursion.

This is my solution

function addNumRecursively(nums){   
    return (nums.length > 1) ? (nums[0]  + addNumRecursively(nums.slice(1))) : nums[0];  
}

console.log(addNumRecursively([1,5,4]));

The output is

rahul@rahul:~/myPractise$ node Recurssion.js 
10

It's working fine.

Is there a better way ?

Rahul Shivsharan
  • 2,481
  • 7
  • 40
  • 59

3 Answers3

2

Reduce is a kind of a loop, just in disguise. Your recursive function application is fine for a solution i think.

If this is a javascript specific question and you wanted to be a little sneaky you could do

function sum(arr){
  return eval(arr.join('+'))
}

Yes eval is considered evil, yes its performance is poor but this could be an alternative solution

eltonkamami
  • 5,134
  • 1
  • 22
  • 30
1

You can use Array reduce as below.

[0, 1, 2, 3, 4].reduce(function(prev, curr) {
  return prev + curr;
});
0

Javascript eval and join function will be useful for all array elements sum without using loop.

var total = eval([0, 1, 2, 3, 4].join("+"));
console.log(total);
Rahul Patel
  • 5,248
  • 2
  • 14
  • 26