How to use recursiveness to iterate in array

Asked

Viewed 69 times

0

I’m looking to implement a recursive function that traverses an array and returns the elements (an alternative to the loop for educational purposes, only).

I did it this way, but he returns to me undefined at the end, since at the last call of the function it does not fall into the if. But the recursive function would not have precisely this purpose, to have an exit condition?

How could improve implementation?

const meuArrayRecursivo = (arr) => {
if (arr.length > 0) {
    let el = arr[0];
    arr.shift();
    return `${el} ${meuArrayRecursivo(arr)}`;
}

//undefined;
};

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

1 answer

1


In fact, in a recursive function, it is crucial to have a stop condition.

But the problem is that when the array has zero size, it does not enter the if, and the function does not find any return. And in these cases, the function ends up returning undefined.

Then you need to return something when the array is empty. In case, as you are mounting a string with the elements, just return an empty string:

function meuArrayRecursivo(arr) {
  if (arr.length > 0) {
    let el = arr[0];
    arr.shift();
    return `${el} ${meuArrayRecursivo(arr)}`;
  }
  return ''; // <--- aqui
};

console.log(meuArrayRecursivo([1, 2])); // 1 2

I also changed the code above to use a function normal. The use of Arrow Function here does not bring any advantage - many people think it is the only way/a "better"/more "modern", etc., but in fact there are some differences (in the specific example there are no, but there are cases where there are, see the documentation for more details - this link is also interesting).


Detail that the method shift, in addition to removing the first element of the array, also returns this element, then you could do so:

function meuArrayRecursivo(arr) {
  if (arr.length > 0) {
    return `${arr.shift()} ${meuArrayRecursivo(arr)}`;
  }
  return '';
};

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

Or so:

function meuArrayRecursivo(arr) {
    return arr.length ? `${arr.shift()} ${meuArrayRecursivo(arr)}` : '';
};

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

  • 1

    Perfect! I still have a lot to improve... but it helped me a lot! =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.