-
-
Save parzibyte/0ab572ac67c8e046e607fe8f4baf2b8e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Dos métodos para invertir arreglos en JavaScript: | |
* algoritmo que intercambia valores dentro del arreglo y otro | |
* que usa una función nativa de los arreglos en JavaScript | |
* | |
* @author parzibyte | |
* Visita: parzibyte.me/blog | |
*/ | |
const invertirManual = arreglo => { | |
// Guardar de una vez la longitud para hacer más legible el código | |
let longitudDelArreglo = arreglo.length; | |
// Recorrer arreglo hasta la mitad. Si es impar, se va al entero anterior más | |
// próximo. P. ej. 5 / 2 => 2 | |
for (let x = 0; x < longitudDelArreglo / 2; x++) { | |
// Respaldar el valor actual | |
let temporal = arreglo[x]; | |
// Calcular el índice contrario, es decir, el del otro lado de la mitad; el cual irá descendiendo | |
let indiceContrario = longitudDelArreglo - x - 1; | |
// En el actual ahora está el del otro lado | |
arreglo[x] = arreglo[indiceContrario]; | |
// Y en el otro lado, el que estaba originalmente en el actual | |
arreglo[indiceContrario] = temporal; | |
} | |
// No regresamos nada porque ya modificamos al arreglo internamente | |
}; | |
const lenguajes = ["PHP", "C", "C#", "Rust", "Java", "JavaScript", "C++", "Go"]; | |
// Imprimir arreglo original | |
console.log("Original: ", lenguajes); | |
// Invertir con método manual | |
invertirManual(lenguajes); | |
console.log("Invertido manualmente: ", lenguajes); | |
// Invertir con método existente | |
lenguajes.reverse(); | |
console.log("Invertido con reverse: ", lenguajes); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment