Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

407
Visualizações
recursive FizzBuzz - why I can't reverse my array?

I am learning recursive functions. For fun, I tried the FizzBuzz coding challenge.

I am stuck as I don't understand why I can't reverse my array inside the recursive function.

Version 1

  const fizzBuzzRecursive = num => {
    let results = [];
    if (num === 1) {
      return '1';
    } else {
      if (num % 3 === 0 && num % 5 === 0) {
        results.push('FizzBuzz');
      } else if (num % 5 === 0) {
        results.push('Buzz');
      } else if (num % 3 === 0) {
        results.push('Fizz');
      } else {
        results.push(''+ num);
      }
      newResults = results.reverse('')
      return newResults.concat(fizzBuzzRecursive(num - 1));
    }
   
  }
  
console.log(fizzBuzzRecursive(5));
// prints [ 'Buzz', '4', 'Fizz', '2', '1' ]

To make it work, I have to place the recursive function inside another function.

Version 2

const fizzBuzz = num => {
  const fizzBuzzRecursive = num => {
    let results = [];
    if (num === 1) {
      return '1';
    } else {
      if (num % 3 === 0 && num % 5 === 0) {
        results.push('FizzBuzz');
      } else if (num % 5 === 0) {
        results.push('Buzz');
      } else if (num % 3 === 0) {
        results.push('Fizz');
      } else {
        results.push(''+ num);
      }
      return results.concat(fizzBuzzRecursive(num - 1));
    }
  }
  
  return fizzBuzzRecursive(num).reverse()
};

console.log(fizzBuzz(5));
// prints [ '1', '2', 'Fizz', '4', 'Buzz' ]

Why does version 1 not properly and is there a way to make it work? Thanks in advance!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In your first example, you are reversing an array with a single element, then concatenating it with the array returned by the next recursive call. In effect, this will not reverse anything, and the results will be concatenated together starting at the deepest level of recursion.

const fizzBuzzRecursive = num => {
    let results = [];
    if (num === 1) {
      return ['1'];
    } else {
      if (num % 3 === 0 && num % 5 === 0) {
        results.push('FizzBuzz');
      } else if (num % 5 === 0) {
        results.push('Buzz');
      } else if (num % 3 === 0) {
        results.push('Fizz');
      } else {
        results.push(''+ num);
      }
      return fizzBuzzRecursive(num - 1).concat(results);
    }
   
  }

console.log(fizzBuzzRecursive(5));
// prints [ '1', '2', 'Fizz', '4', 'Buzz' ]

To achieve the reversal, simply swap the order of the concatenation, also making sure to return ['1'] inside of an array as your base case to make sure that it is able to concatenate with the other recursive calls.

about 4 years ago · Juan Pablo Isaza Relatório

0

have a look at the below to reverse an array

Option 1

let arr = ['Buzz', '4', 'Fizz', '2', '1' ];
console.log(arr); // returns ['Buzz', '4', 'Fizz', '2', '1']
arr.reverse(); 
console.log(arr); // returns ['1', '2', 'Fizz', '4', 'Buzz']

NB arr.reverse actually modifys the array.

Option 2

function recursive(array){
    let result = [];
  array.forEach((value, index) => {
    result.unshift(value);
  })
  return result;
}  
console.log(recursive(arr)); // returns ['1', '2', 'Fizz', '4', 'Buzz']

Option 2 explanation loops through the arr and unshift the value. The unshift() method adds new items to the beginning of an array.

  • first time is adds ['Buzz'] to result array
  • second time it adds ['4', Buzz] to result array
  • third time is adds ['Fizz', '4', 'Buzz'] to result array
  • fourth time is adds ['2', 'Fizz', '4', 'Buzz'] to result array
  • fifth time is adds ['1', '2', 'Fizz', '4', 'Buzz'] to result array
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda