1

Get the length of an array using recursion without accessing its length property.

My Code Below:

function getLength(array, count=0) {

  if (array.length === 0){
    return 0
  }

  else {
    count ++; 

    array.pop()
    return getLength(array, count)
  }
  return count; 
}

// To check if you've completed the challenge, uncomment these console.logs!
console.log(getLength([1])); // -> 1
console.log(getLength([1, 2])); // -> 2
console.log(getLength([1, 2, 3, 4, 5])); // -> 5
console.log(getLength([], 0)); // -> 0

When I run my code on the third console.log:

console.log(getLength([1, 2])); 

it returns 0 instead of 2

What am I doing wrong?

///////////////////////////////////////////////////////////////////////////

figured it out:

function getLength(array, count=0) {

  if (array.length === 0){
    return count
  }

  else {
    count ++; 

    array.pop()
    return getLength(array, count)
  } 
}
9
  • really a dupe?? Commented Jun 14, 2019 at 21:14
  • Cause you return 0. Commented Jun 14, 2019 at 21:14
  • @ninaScholz no, I'm not sure wether the OP uses us to solve code challenges. Thats up to a debate. Commented Jun 14, 2019 at 21:14
  • 1
    @PineNuts0, you still use length. Commented Jun 14, 2019 at 21:15
  • Feel free to self answer then :) Commented Jun 14, 2019 at 21:17

2 Answers 2

2

You could check if the item at index zero exists. This works only for non sparse arrays.

function getLength(array) {
    return 0 in array ? 1 + getLength(array.slice(1)) : 0;
}

console.log(getLength([1]));             // 1
console.log(getLength([1, 2]));          // 2
console.log(getLength([1, 2, 3, 4, 5])); // 5
console.log(getLength([], 0));           // 0

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

Comments

1

Another simple solution (which also does not work on sparse arrays) is

const len1 = arr => arr.reduce(n => n + 1, 0)

And a related, but less simple, one does work on sparse arrays:

const len2 = (arr) => Array.from(arr, _ => 1).reduce(n => n + 1, 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.