Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
Reversing an array in JS

I've looked at SO to see what's been said about this and I've done my homework regarding this subject but, in the solution to this problem from Eloquent JavaScript, I've done the following:

function reversedArray(array) {
    let reversedArray = [];
    for (let i = 0; i <= array.length; i++) {
        reversedArray.push(array[array.length - i]);
    }
    return reversedArray;
}
let arr = [
    1,
    2,
    3,
    4
];
console.log(arr);
console.log(reversedArray(arr));

There, I obtained this:

> 1,2,3,4
> ,4,3,2,1

Which means that the array.length of the reversed array is now longer than the original array by an extra element. Of course, I fixed my code to eliminate the first element of the reversed array like this:

function reversedArray(array) {
    let reversedArray = [];
    for (let i = 0; i <= array.length; i++) {
        reversedArray.push(array[array.length - i]);
    }
    reversedArray.shift();
    return reversedArray;
}
let arr = [
    1,
    2,
    3,
    4
];
console.log(arr);
console.log(reversedArray(arr));

And it worked as expected producing:

> 1,2,3,4
> 4,3,2,1

I am starting to learn JS and I can't see why the reversed array has an extra element. Can somebody explain it to me? I don't feel it is right to just eliminate the element that's extra and move on with life... I have looked at some other solutions and they are fine but I just want to learn please, why is it that my function increases the array length? Many thanks!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If you loop backwards, you do not need to perform any index subtraction.

const reversedArray = (array) => {
  const result = [];
  for (let i = array.length - 1; i >= 0; i--) {
    result.push(array[i]);
  }
  return result;
};

console.log(reversedArray([1, 2, 3, 4, 5]));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda