0

for ex: I have this array

arr=[1,3,7,8];
1st call will result in: [4,8,9]
2nd Call will result in:[12,13]
3rd call will result in:[25]

How to do this using recursion in javascript?
2
  • 2
    Have you tried anything? Without any evidence of what you already know, it's pretty difficult to write a high quality answer that addresses what you don't understand. This site isn't just a code-writing service. Commented May 23, 2017 at 0:26
  • Are you looking for sum = ([h,...t]) => h && sum(t.map(a => a + h)) || h? Commented May 23, 2017 at 0:46

2 Answers 2

1

You have 3 cases to consider

  1. when an empty array is provided, return an empty array
  2. when an an array of 1 element is provided, return the same array
  3. when an array of 2 or more elements is provided, return the tail of the array with each element of the tail added to the head

const foo = ([x,...xs]) => {
  if (x === undefined)
    return []
  else if (xs.length === 0)
    return [x]
  else
    return foo(xs.map(y => x + y))
}

console.log(foo([]))        // []
console.log(foo([1]))       // [1]
console.log(foo([1,3]))     // [4]
console.log(foo([1,3,7]))   // [12]
console.log(foo([1,3,7,8])) // [25]

The function could be improved if you separate some of the concerns by writing some helpers

const add = x => y => x + y

const isEmpty = xs => xs.length === 0

const isNull = x => x == null

const foo = ([x,...xs]) => {
  if (isNull(x))
    return []
  else if (isEmpty(xs))
    return [x]
  else
    return foo(xs.map(add(x)))
}

console.log(foo([]))        // []
console.log(foo([1]))       // [1]
console.log(foo([1,3]))     // [4]
console.log(foo([1,3,7]))   // [12]
console.log(foo([1,3,7,8])) // [25]

Sign up to request clarification or add additional context in comments.

Comments

1

I don't know why you want to do it recursively, but this is one possible solution -

function sum(arr){
  // base case
  if(arr.length === 1 || arr.length === 0) {
    return arr
  } else {
    return sum(arr.slice(1).map(el => el + arr[0]))
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.