Search code examples
javascriptarraysrecursionecmascript-6ecmascript-5

Javascript: Recursively count the sum of all elements in array?


I'm trying to write a recursive function to count the number of items in a array using Javascript.

I can do it in Python:

def count(list):
 if list == []:
  return 0
 return 1 + count(list[1:]) 

How can I do it in ES5 and ES6?


Solution

  • Counting elements is ridicoulous since you can just take the length property. It will be O(1) and do what you expect. As for summing or doing something with the elements:

    // recursively. Works only on arrays 
    const sumElements = (arr) => {
      if (arr.length === 1) return arr[0];
    
      const [e, ...rest] = arr;
      return e + sumElements(rest);
    }
    
    
    // recursively and effiecent. Works only on arrays
    const sumElements = (arr) => {
      const helper = (index, acc) => index < 0 ? acc helper(index - 1, acc + arr[index]);
      return helper(arr.length-1, 0);
    }
    
    
    // using higher order functions. Works for all collections that has reduce defined
    const sumElements = list => list.reduce((acc, e) => acc + e), 0);
    
    // using iterators. Works for all collections that has iterator defined
    const sumElements = (list) => {
      let sum = 0;
      for (const e of list) {
        sum += e;
      }
      return sum;
    }