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

241
Visualizações
reversing an array in javascript in function without method reverse()

here is my code:

const reverseArr = (...args) => {
  let length   = args.length - 1
  let reversed = []
  let i        = 0
  for (let a = length - i; i <= length; i++) {
    args[a] = reversed[i]
  }
  return reversed
}

console.log( reverseArr(3, 5, 4, 1) )

What's the problem here? Does it about value of 'i' or lenght?

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

0

const numbers = [1, 2, 3, 4, 5];

const reverse = (array) => {
    const reversed = [];
    for (const [index, element] of numbers.entries())
        reversed[array.length - index - 1] = element;
    return reversed;
}

console.log(reverse(numbers)); // [ 5, 4, 3, 2, 1 ] 

We can use a for ... of loop on the entries of the array we want to reverse, and push the element into the desired position of the array.

To calculate the position we want, we can just do array length - index - 1.

This means that if we have an array of 5 items, [1, 2, 3, 4, 5] and we iterate through, we will be doing...

  1. 5 - 0 - 1 = 4 for the index of the first item.
  2. 5 - 1 - 1 = 3 for the index of the second item.
  3. 5 - 2 - 1 = 2 for the index of the third item.
  4. 5 - 3 - 1 = 1 for the index of the fourth item.
  5. 5 - 4 - 1 = 0 for the index of the fifth item.
about 4 years ago · Juan Pablo Isaza Relatório

0

function reverse(arr){
// get length
var len = arr.length;
// create new array
var newArr = [];
// loop through array
for(var i = len - 1; i >= 0; i--){
    // push to new array
    newArr.push(arr[i]);
}
// return new array
return newArr;}

reverse([1,2,3,4,5]);

try this.

about 4 years ago · Juan Pablo Isaza Relatório

0

There are multiple issues :

  1. for initialisation happens once, so if you do let a = lemgth - i, it doesn't update a any further, even though i changes.
  2. You're reassigning values to your input array itself with reversed array, which is empty itself.
  3. You're output-ing the input array (arr).

I tried to fix your snippet, and also adding better approach:

const reverseArr = (...args) => {
      let length = args.length - 1
      let reversed = []
      let i = 0
      // update 'a' as soon as you update 'i'
      for(let a = length - i; i <= length; i++, a = length - i){
        // update the standby array 'reveresed'
        reversed[i] = args[a]
      }
      // print the reversed array instead of 'args' 
      console.log(reversed)
    }


// Alternate approach (in-place reverse)
const reverseInput = (...args) => {
  let left = 0, right = args.length - 1;
  while(left <= right) {
    // swap the left and right elements in  array
    [args[left], args[right]] = [args[right], args[left]] ;
    left++;
    right--;
  }
  console.log(args);
}

    // Approach 1
    console.log(reverseArr(3, 5, 4, 1))
    // Approach 2
    console.log(reverseInput(3,5,4,1));

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