diff --git a/1-js/05-data-types/05-array-methods/1-camelcase/_js.view/solution.js b/1-js/05-data-types/05-array-methods/1-camelcase/_js.view/solution.js index 490f570ad..e390cf5cb 100644 --- a/1-js/05-data-types/05-array-methods/1-camelcase/_js.view/solution.js +++ b/1-js/05-data-types/05-array-methods/1-camelcase/_js.view/solution.js @@ -1,10 +1,10 @@ function camelize(str) { return str - .split('-') // splits 'my-long-word' into array ['my', 'long', 'word'] + .split('-') // separa 'my-long-word' en el array ['my', 'long', 'word'] .map( - // capitalizes first letters of all array items except the first one - // converts ['my', 'long', 'word'] into ['my', 'Long', 'Word'] + // convierte en mayúscula todas las primeras letras de los elementos del array excepto por el primero + // convierte ['my', 'long', 'word'] en ['my', 'Long', 'Word'] (word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1) ) - .join(''); // joins ['my', 'Long', 'Word'] into 'myLongWord' + .join(''); // une ['my', 'Long', 'Word'] en 'myLongWord' } diff --git a/1-js/05-data-types/05-array-methods/1-camelcase/task.md b/1-js/05-data-types/05-array-methods/1-camelcase/task.md index ef5944636..4b8b311d1 100644 --- a/1-js/05-data-types/05-array-methods/1-camelcase/task.md +++ b/1-js/05-data-types/05-array-methods/1-camelcase/task.md @@ -2,13 +2,13 @@ importance: 5 --- -# Translate border-left-width to borderLeftWidth +# Transforma border-left-width en borderLeftWidth -Write the function `camelize(str)` that changes dash-separated words like "my-short-string" into camel-cased "myShortString". +Escribe la función `camelize(str)` que convierta palabras separadas por guión como "mi-cadena-corta" en palabras con mayúscula "miCadenaCorta". -That is: removes all dashes, each word after dash becomes uppercased. +Esto sería: remover todos los guiones y que cada palabra después de un guión comience con mayúscula. -Examples: +Ejemplos: ```js camelize("background-color") == 'backgroundColor'; @@ -16,4 +16,4 @@ camelize("list-style-image") == 'listStyleImage'; camelize("-webkit-transition") == 'WebkitTransition'; ``` -P.S. Hint: use `split` to split the string into an array, transform it and `join` back. +P.D. Pista: usa `split` para dividir el string en un array, transfórmalo y vuelve a unirlo (`join`). diff --git a/1-js/05-data-types/05-array-methods/10-average-age/task.md b/1-js/05-data-types/05-array-methods/10-average-age/task.md index bf5f85df3..f32a5a8c9 100644 --- a/1-js/05-data-types/05-array-methods/10-average-age/task.md +++ b/1-js/05-data-types/05-array-methods/10-average-age/task.md @@ -2,13 +2,13 @@ importance: 4 --- -# Get average age +# Obtener edad promedio -Write the function `getAverageAge(users)` that gets an array of objects with property `age` and returns the average age. +Escribe la función `getAverageAge(users)` que obtenga un array de objetos con la propiedad `age` y devuelva el promedio de `age`. -The formula for the average is `(age1 + age2 + ... + ageN) / N`. +La fórmula de promedio es `(age1 + age2 + ... + ageN) / N`. -For instance: +Por ejemplo: ```js no-beautify let john = { name: "John", age: 25 }; diff --git a/1-js/05-data-types/05-array-methods/11-array-unique/solution.md b/1-js/05-data-types/05-array-methods/11-array-unique/solution.md index b9d627a0a..69253da4a 100644 --- a/1-js/05-data-types/05-array-methods/11-array-unique/solution.md +++ b/1-js/05-data-types/05-array-methods/11-array-unique/solution.md @@ -1,6 +1,7 @@ -Let's walk the array items: -- For each item we'll check if the resulting array already has that item. +Recorramos los elementos dentro del array: +- Para cada elemento vamos a comprobar si el array resultante ya tiene ese elemento. - If it is so, then ignore, otherwise add to results. +- Si ya lo tiene ignora y continúa, si no, agrega el resultado. ```js run demo function unique(arr) { @@ -22,18 +23,18 @@ let strings = ["Hare", "Krishna", "Hare", "Krishna", alert( unique(strings) ); // Hare, Krishna, :-O ``` -The code works, but there's a potential performance problem in it. +El código funciona pero tiene un problema potencial de desempeño. -The method `result.includes(str)` internally walks the array `result` and compares each element against `str` to find the match. +El método `result.includes(str)` internamente recorre el array `result` y compara cada elemento con `str` para encontrar una coincidencia. -So if there are `100` elements in `result` and no one matches `str`, then it will walk the whole `result` and do exactly `100` comparisons. And if `result` is large, like `10000`, then there would be `10000` comparisons. +Por lo tanto, si hay `100` elementos en `result` y ninguno coincide con `str`, entonces habrá recorrido todo el array `result` y ejecutado `100` comparaciones. Y si `result` es tan grande como `10000`, entonces habrá `10000` comparaciones. -That's not a problem by itself, because JavaScript engines are very fast, so walk `10000` array is a matter of microseconds. +Esto no es un problema en sí mismo, porque los motores JavaScript son muy rápidos, por lo que recorrer `10000` elementos de un array solo le tomaría microsegundos. -But we do such test for each element of `arr`, in the `for` loop. +Pero ejecutamos dicha comprobación para cada elemento de `arr` en el loop `for`. -So if `arr.length` is `10000` we'll have something like `10000*10000` = 100 millions of comparisons. That's a lot. +Entonces si `arr.length` es `10000` vamos a tener algo como `10000*10000` = 100 millones de comparaciones. Esto es realmente mucho. -So the solution is only good for small arrays. +Por lo que la solución solo es buena para arrays pequeños. -Further in the chapter we'll see how to optimize it. +Más adelante en el capítulo vamos a ver como optimizarlo. diff --git a/1-js/05-data-types/05-array-methods/11-array-unique/task.md b/1-js/05-data-types/05-array-methods/11-array-unique/task.md index 5b56d3621..11495a299 100644 --- a/1-js/05-data-types/05-array-methods/11-array-unique/task.md +++ b/1-js/05-data-types/05-array-methods/11-array-unique/task.md @@ -2,17 +2,17 @@ importance: 4 --- -# Filter unique array members +# Filtrar elementos únicos de un array -Let `arr` be an array. +Partiendo del array `arr`. -Create a function `unique(arr)` that should return an array with unique items of `arr`. +Crea una función `unique(arr)` que devuelva un array con los elementos que se encuentran una sola vez dentro de `arr`. -For instance: +Por ejemplo: ```js function unique(arr) { - /* your code */ + /* tu código */ } let strings = ["Hare", "Krishna", "Hare", "Krishna", diff --git a/1-js/05-data-types/05-array-methods/12-reduce-object/task.md b/1-js/05-data-types/05-array-methods/12-reduce-object/task.md index d3c8f8eb1..015a56946 100644 --- a/1-js/05-data-types/05-array-methods/12-reduce-object/task.md +++ b/1-js/05-data-types/05-array-methods/12-reduce-object/task.md @@ -2,13 +2,13 @@ importance: 4 --- -# Create keyed object from array +# Crea un objeto a partir de un array -Let's say we received an array of users in the form `{id:..., name:..., age... }`. +Supongamos que recibimos un array de usuarios con la forma `{id:..., name:..., age... }`. -Create a function `groupById(arr)` that creates an object from it, with `id` as the key, and array items as values. +Crea una función `groupById(arr)` que cree un objeto, con `id` como clave (key) y los elementos del array como valores. -For example: +Por ejemplo: ```js let users = [ @@ -20,7 +20,7 @@ let users = [ let usersById = groupById(users); /* -// after the call we should have: +// después de llamar a la función deberíamos tener: usersById = { john: {id: 'john', name: "John Smith", age: 20}, @@ -30,8 +30,8 @@ usersById = { */ ``` -Such function is really handy when working with server data. +Dicha función es realmente útil cuando trabajamos con información del servidor. -In this task we assume that `id` is unique. There may be no two array items with the same `id`. +Para esta actividad asumimos que cada `id` es único. No existen dos elementos del array con el mismo `id`. -Please use array `.reduce` method in the solution. +Usa el método `array.reduce` en la solución. diff --git a/1-js/05-data-types/05-array-methods/2-filter-range/_js.view/solution.js b/1-js/05-data-types/05-array-methods/2-filter-range/_js.view/solution.js index 0bdfbae5a..05f81afaf 100644 --- a/1-js/05-data-types/05-array-methods/2-filter-range/_js.view/solution.js +++ b/1-js/05-data-types/05-array-methods/2-filter-range/_js.view/solution.js @@ -1,5 +1,5 @@ function filterRange(arr, a, b) { - // added brackets around the expression for better readability + // agregamos paréntesis en torno a la expresión para mayor legibilidad return arr.filter(item => (a <= item && item <= b)); } \ No newline at end of file diff --git a/1-js/05-data-types/05-array-methods/2-filter-range/solution.md b/1-js/05-data-types/05-array-methods/2-filter-range/solution.md index 73993a07a..e8b70be6c 100644 --- a/1-js/05-data-types/05-array-methods/2-filter-range/solution.md +++ b/1-js/05-data-types/05-array-methods/2-filter-range/solution.md @@ -1,6 +1,6 @@ ```js run demo function filterRange(arr, a, b) { - // added brackets around the expression for better readability + // agregamos paréntesis en torno a la expresión para mayor legibilidad return arr.filter(item => (a <= item && item <= b)); } @@ -8,7 +8,7 @@ let arr = [5, 3, 8, 1]; let filtered = filterRange(arr, 1, 4); -alert( filtered ); // 3,1 (matching values) +alert( filtered ); // 3,1 (valores dentro del rango) -alert( arr ); // 5,3,8,1 (not modified) +alert( arr ); // 5,3,8,1 (array original no modificado) ``` diff --git a/1-js/05-data-types/05-array-methods/2-filter-range/task.md b/1-js/05-data-types/05-array-methods/2-filter-range/task.md index 18b2c1d9b..2f06d5ef6 100644 --- a/1-js/05-data-types/05-array-methods/2-filter-range/task.md +++ b/1-js/05-data-types/05-array-methods/2-filter-range/task.md @@ -2,21 +2,21 @@ importance: 4 --- -# Filter range +# Filtrar un rango -Write a function `filterRange(arr, a, b)` that gets an array `arr`, looks for elements between `a` and `b` in it and returns an array of them. +Escribe una función `filterRange(arr, a, b)` que obtenga un array `arr`, busque los elementos entre `a` y `b` y devuelva un array con los resultados. -The function should not modify the array. It should return the new array. +La función no debe modificar el array. Debe devolver un nuevo array. -For instance: +Por ejemplo: ```js let arr = [5, 3, 8, 1]; let filtered = filterRange(arr, 1, 4); -alert( filtered ); // 3,1 (matching values) +alert( filtered ); // 3,1 (valores dentro del rango) -alert( arr ); // 5,3,8,1 (not modified) +alert( arr ); // 5,3,8,1 (array original no modificado) ``` diff --git a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/_js.view/solution.js b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/_js.view/solution.js index 488db3755..f21e5be67 100644 --- a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/_js.view/solution.js +++ b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/_js.view/solution.js @@ -4,7 +4,7 @@ function filterRangeInPlace(arr, a, b) { for (let i = 0; i < arr.length; i++) { let val = arr[i]; - // remove if outside of the interval + // remueve aquellos elementos que se encuentran fuera del intervalo if (val < a || val > b) { arr.splice(i, 1); i--; diff --git a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/solution.md b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/solution.md index 36e3130ff..a18159879 100644 --- a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/solution.md +++ b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/solution.md @@ -4,7 +4,7 @@ function filterRangeInPlace(arr, a, b) { for (let i = 0; i < arr.length; i++) { let val = arr[i]; - // remove if outside of the interval + // remueve aquellos elementos que se encuentran fuera del intervalo if (val < a || val > b) { arr.splice(i, 1); i--; @@ -15,7 +15,7 @@ function filterRangeInPlace(arr, a, b) { let arr = [5, 3, 8, 1]; -filterRangeInPlace(arr, 1, 4); // removed the numbers except from 1 to 4 +filterRangeInPlace(arr, 1, 4); // remueve los números excepto aquellos entre 1 y 4 alert( arr ); // [3, 1] ``` diff --git a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/task.md b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/task.md index 7066a51ab..b131b0952 100644 --- a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/task.md +++ b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/task.md @@ -2,17 +2,17 @@ importance: 4 --- -# Filter range "in place" +# Filtrar rango "en el lugar" -Write a function `filterRangeInPlace(arr, a, b)` that gets an array `arr` and removes from it all values except those that are between `a` and `b`. The test is: `a ≤ arr[i] ≤ b`. +Escribe una función `filterRangeInPlace(arr, a, b)` que obtenga un array `arr` y remueva del mismo todos los valores excepto aquellos que se encuentran entre `a` y `b`. El test es: `a ≤ arr[i] ≤ b`. -The function should only modify the array. It should not return anything. +La función solo debe modificar el array. No debe devolver nada. -For instance: +Por ejemplo: ```js let arr = [5, 3, 8, 1]; -filterRangeInPlace(arr, 1, 4); // removed the numbers except from 1 to 4 +filterRangeInPlace(arr, 1, 4); // remueve los números excepto aquellos entre 1 y 4 alert( arr ); // [3, 1] ``` diff --git a/1-js/05-data-types/05-array-methods/4-sort-back/task.md b/1-js/05-data-types/05-array-methods/4-sort-back/task.md index 0e3eeab76..d09e47b2b 100644 --- a/1-js/05-data-types/05-array-methods/4-sort-back/task.md +++ b/1-js/05-data-types/05-array-methods/4-sort-back/task.md @@ -2,12 +2,12 @@ importance: 4 --- -# Sort in decreasing order +# Ordenar en orden decreciente ```js let arr = [5, 2, 1, -10, 8]; -// ... your code to sort it in decreasing order +// ... tu código para ordenar en orden decreciente alert( arr ); // 8, 5, 2, 1, -10 ``` diff --git a/1-js/05-data-types/05-array-methods/5-copy-sort-array/solution.md b/1-js/05-data-types/05-array-methods/5-copy-sort-array/solution.md index 8537b129e..3c09c956a 100644 --- a/1-js/05-data-types/05-array-methods/5-copy-sort-array/solution.md +++ b/1-js/05-data-types/05-array-methods/5-copy-sort-array/solution.md @@ -1,4 +1,4 @@ -We can use `slice()` to make a copy and run the sort on it: +Podemos usar `slice()` para crear una copia y realizar el ordenamiento en ella: ```js run function copySorted(arr) { diff --git a/1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md b/1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md index c1395b4ad..14e0a8c13 100644 --- a/1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md +++ b/1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md @@ -2,11 +2,11 @@ importance: 5 --- -# Copy and sort array +# Copia y ordena un array -We have an array of strings `arr`. We'd like to have a sorted copy of it, but keep `arr` unmodified. +Supongamos que tenemos un array `arr`. Nos gustaría tener una copia ordenada del mismo, pero mantener `arr` sin modificar. -Create a function `copySorted(arr)` that returns such a copy. +Crea una función `copySorted(arr)` que devuelva esa copia. ```js let arr = ["HTML", "JavaScript", "CSS"]; @@ -14,5 +14,5 @@ let arr = ["HTML", "JavaScript", "CSS"]; let sorted = copySorted(arr); alert( sorted ); // CSS, HTML, JavaScript -alert( arr ); // HTML, JavaScript, CSS (no changes) +alert( arr ); // HTML, JavaScript, CSS (sin cambios) ``` diff --git a/1-js/05-data-types/05-array-methods/6-array-get-names/task.md b/1-js/05-data-types/05-array-methods/6-array-get-names/task.md index 74c8a9d74..6ed10e946 100644 --- a/1-js/05-data-types/05-array-methods/6-array-get-names/task.md +++ b/1-js/05-data-types/05-array-methods/6-array-get-names/task.md @@ -2,11 +2,11 @@ importance: 5 --- -# Map to names +# Mapa a nombres -You have an array of `user` objects, each one has `user.name`. Write the code that converts it into an array of names. +Tienes un array de objetos `user`, cada uno tiene `user.name`. Escribe el código que lo convierta en un array de nombres. -For instance: +Por ejemplo: ```js no-beautify let john = { name: "John", age: 25 }; @@ -15,7 +15,7 @@ let mary = { name: "Mary", age: 28 }; let users = [ john, pete, mary ]; -let names = /* ... your code */ +let names = /* ... tu código */ alert( names ); // John, Pete, Mary ``` diff --git a/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md b/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md index ebe0714cf..e44346749 100644 --- a/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md +++ b/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md @@ -1,3 +1,3 @@ -- Please note how methods are stored. They are simply added to `this.methods` property. -- All tests and numeric conversions are done in the `calculate` method. In future it may be extended to support more complex expressions. +- Por favor ten en cuenta cómo son almacenados los métodos. Simplemente son agregados a la propiedad `this.methods`. +- Todos los test y conversiones son hechas con el método `calculate`. En el futuro puede ser extendido para soportar expresiones más complejas. diff --git a/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md b/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md index e0d302f4c..f8888d806 100644 --- a/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md +++ b/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md @@ -2,24 +2,24 @@ importance: 5 --- -# Create an extendable calculator +# Crea una calculadora extensible -Create a constructor function `Calculator` that creates "extendable" calculator objects. +Crea una función `Calculator` que cree objetos calculadores "extensibles". -The task consists of two parts. +La actividad consiste de dos partes. -1. First, implement the method `calculate(str)` that takes a string like `"1 + 2"` in the format "NUMBER operator NUMBER" (space-delimited) and returns the result. Should understand plus `+` and minus `-`. +1. Primero, implementar el método `calculate(str)` que toma un string como `"1 + 2"` en el formato "NUMERO operador NUMERO" (delimitado por espacios) y devuelve el resultado. Debe entender más `+` y menos `-`. - Usage example: + Ejemplo de uso: ```js let calc = new Calculator; alert( calc.calculate("3 + 7") ); // 10 ``` -2. Then add the method `addMethod(name, func)` that teaches the calculator a new operation. It takes the operator `name` and the two-argument function `func(a,b)` that implements it. +2. Luego agrega el método `addMethod(name, func)` que enseñe a la calculadora una nueva operación. Toma el operador `name` y la función con dos argumentos `func(a,b)` que lo implementa. - For instance, let's add the multiplication `*`, division `/` and power `**`: + Por ejemplo, vamos a agregar la multiplicación `*`, division `/` y potencia `**`: ```js let powerCalc = new Calculator; @@ -31,6 +31,6 @@ The task consists of two parts. alert( result ); // 8 ``` -- No parentheses or complex expressions in this task. -- The numbers and the operator are delimited with exactly one space. -- There may be error handling if you'd like to add it. +- Sin paréntesis ni expresiones complejas. +- Los números y el operador deben estar delimitados por exactamente un espacio. +- Puede haber manejo de errores si quisieras agregarlo. diff --git a/1-js/05-data-types/05-array-methods/7-map-objects/solution.md b/1-js/05-data-types/05-array-methods/7-map-objects/solution.md index 5d8bf4a13..5c98a0b7c 100644 --- a/1-js/05-data-types/05-array-methods/7-map-objects/solution.md +++ b/1-js/05-data-types/05-array-methods/7-map-objects/solution.md @@ -25,9 +25,9 @@ alert( usersMapped[0].id ); // 1 alert( usersMapped[0].fullName ); // John Smith ``` -Please note that in for the arrow functions we need to use additional brackets. +Ten en cuenta que para las funciones arrow necesitamos usar paréntesis adicionales. -We can't write like this: +No podemos escribirlo de la siguiente manera: ```js let usersMapped = users.map(user => *!*{*/!* fullName: `${user.name} ${user.surname}`, @@ -35,9 +35,9 @@ let usersMapped = users.map(user => *!*{*/!* }); ``` -As we remember, there are two arrow functions: without body `value => expr` and with body `value => {...}`. +Como recordarás, existen dos funciones arrow: sin cuerpo `value => expr` y con cuerpo `value => {...}`. -Here JavaScript would treat `{` as the start of function body, not the start of the object. The workaround is to wrap them in the "normal" brackets: +Acá JavaScript tratará `{` como el inicio de cuerpo de la función, no el inicio del objeto. La manera de resolver esto es encerrarlo dentro de paréntesis: ```js let usersMapped = users.map(user => *!*({*/!* @@ -46,6 +46,4 @@ let usersMapped = users.map(user => *!*({*/!* })); ``` -Now fine. - - +Ahora funciona. diff --git a/1-js/05-data-types/05-array-methods/7-map-objects/task.md b/1-js/05-data-types/05-array-methods/7-map-objects/task.md index b11d12155..a66e98e2b 100644 --- a/1-js/05-data-types/05-array-methods/7-map-objects/task.md +++ b/1-js/05-data-types/05-array-methods/7-map-objects/task.md @@ -2,13 +2,13 @@ importance: 5 --- -# Map to objects +# Mapa a objetos -You have an array of `user` objects, each one has `name`, `surname` and `id`. +Tienes un array de objetos `user`, cada uno tiene `name`, `surname` e `id`. -Write the code to create another array from it, of objects with `id` and `fullName`, where `fullName` is generated from `name` and `surname`. +Escribe el código para crear otro array a partir de este, de objetos con `id` y `fullName`, donde `fullName` es generado a partir de `name` y `surname`. -For instance: +Por ejemplo: ```js no-beautify let john = { name: "John", surname: "Smith", id: 1 }; @@ -18,7 +18,7 @@ let mary = { name: "Mary", surname: "Key", id: 3 }; let users = [ john, pete, mary ]; *!* -let usersMapped = /* ... your code ... */ +let usersMapped = /* ... tu código ... */ */!* /* @@ -33,4 +33,4 @@ alert( usersMapped[0].id ) // 1 alert( usersMapped[0].fullName ) // John Smith ``` -So, actually you need to map one array of objects to another. Try using `=>` here. There's a small catch. \ No newline at end of file +Entonces, en realidad lo que necesitas es mapear un array de objetos a otro. Intenta usar `=>` en este caso. Hay un pequeño truco. \ No newline at end of file diff --git a/1-js/05-data-types/05-array-methods/8-sort-objects/solution.md b/1-js/05-data-types/05-array-methods/8-sort-objects/solution.md index 9f1ade707..29a881cf0 100644 --- a/1-js/05-data-types/05-array-methods/8-sort-objects/solution.md +++ b/1-js/05-data-types/05-array-methods/8-sort-objects/solution.md @@ -11,7 +11,7 @@ let arr = [ pete, john, mary ]; sortByAge(arr); -// now sorted is: [john, mary, pete] +// ahora ordenado es: [john, mary, pete] alert(arr[0].name); // John alert(arr[1].name); // Mary alert(arr[2].name); // Pete diff --git a/1-js/05-data-types/05-array-methods/8-sort-objects/task.md b/1-js/05-data-types/05-array-methods/8-sort-objects/task.md index 9a215c9f4..768eaafe5 100644 --- a/1-js/05-data-types/05-array-methods/8-sort-objects/task.md +++ b/1-js/05-data-types/05-array-methods/8-sort-objects/task.md @@ -2,11 +2,11 @@ importance: 5 --- -# Sort users by age +# Ordena usuarios por edad -Write the function `sortByAge(users)` that gets an array of objects with the `age` property and sorts them by `age`. +Escribe la función `sortByAge(users)` que cree un array de objetos con al propiedad `age` y los ordene según `age`. -For instance: +Por ejemplo: ```js no-beautify let john = { name: "John", age: 25 }; @@ -17,7 +17,7 @@ let arr = [ pete, john, mary ]; sortByAge(arr); -// now: [john, mary, pete] +// ahora: [john, mary, pete] alert(arr[0].name); // John alert(arr[1].name); // Mary alert(arr[2].name); // Pete diff --git a/1-js/05-data-types/05-array-methods/9-shuffle/solution.md b/1-js/05-data-types/05-array-methods/9-shuffle/solution.md index 6674c444f..438131cbf 100644 --- a/1-js/05-data-types/05-array-methods/9-shuffle/solution.md +++ b/1-js/05-data-types/05-array-methods/9-shuffle/solution.md @@ -1,4 +1,4 @@ -The simple solution could be: +Una solución simple podría ser: ```js run *!* @@ -12,18 +12,18 @@ shuffle(arr); alert(arr); ``` -That somewhat works, because `Math.random() - 0.5` is a random number that may be positive or negative, so the sorting function reorders elements randomly. +Eso funciona de alguna manera, porque `Math.random() - 0.5` es un número aleatorio que puede ser positivo o negativo, por lo tanto, la función de ordenamiento reordena los elementos de forma aleatoria. -But because the sorting function is not meant to be used this way, not all permutations have the same probability. +Pero debido a que la función de ordenamiento no está hecha para ser usada de esta manera, no todas las permutaciónes tienen la misma probabilidad. -For instance, consider the code below. It runs `shuffle` 1000000 times and counts appearances of all possible results: +Por ejemplo, consideremos el código siguiente. Ejecuta `shuffle` 1000000 veces y cuenta las apariciones de todos los resultados posibles: ```js run function shuffle(array) { array.sort(() => Math.random() - 0.5); } -// counts of appearances for all possible permutations +// cuenta las apariciones para todas las permutaciones posibles let count = { '123': 0, '132': 0, @@ -39,13 +39,13 @@ for (let i = 0; i < 1000000; i++) { count[array.join('')]++; } -// show counts of all possible permutations +// muestra conteo de todas las permutaciones posibles for (let key in count) { alert(`${key}: ${count[key]}`); } ``` -An example result (depends on JS engine): +Un resultado de ejemplo (depende del motor JS): ```js 123: 250706 @@ -56,30 +56,31 @@ An example result (depends on JS engine): 321: 125223 ``` -We can see the bias clearly: `123` and `213` appear much more often than others. +Podemos ver una clara tendencia: `123` y `213` aparecen mucho más seguido que otros. -The result of the code may vary between JavaScript engines, but we can already see that the approach is unreliable. +El resultado del código puede variar entre distitos motores JavaScript pero ya podemos ver que esta forma de abordar el problema es poco confiable. Why it doesn't work? Generally speaking, `sort` is a "black box": we throw an array and a comparison function into it and expect the array to be sorted. But due to the utter randomness of the comparison the black box goes mad, and how exactly it goes mad depends on the concrete implementation that differs between engines. +¿Por qué no funciona? Generalmente hablando, `sort` es una "caja negra": tiramos dentro un array y una función de ordenamiento y esperamos que el array se ordene. Pero debido a la total aleatoriedad de la comparación, la caja negra se vuelve loca y exactamente en que sentido se vuelve loca depende de la implementación específica, que difiere de un motor a otro. -There are other good ways to do the task. For instance, there's a great algorithm called [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). The idea is to walk the array in the reverse order and swap each element with a random one before it: +Existen otra formas mejores de realizar la tarea. Por ejemplo, hay un excelente algorítmo llamado [Algoritmo de Fisher-Yates](https://es.wikipedia.org/wiki/Algoritmo_de_Fisher-Yates). La idea es recorrer el array en sentido inverso e intercambiar cada elemento con un elemento aleatorio anterior: ```js function shuffle(array) { for (let i = array.length - 1; i > 0; i--) { - let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i + let j = Math.floor(Math.random() * (i + 1)); // índice aleatorio entre 0 e i - // swap elements array[i] and array[j] - // we use "destructuring assignment" syntax to achieve that - // you'll find more details about that syntax in later chapters - // same can be written as: + // intercambia elementos array[i] y array[j] + // usamos la sintáxis "asignación de desestructuración" para lograr eso + // encontrarás más información acerca de esa sntáxis en los capítulos siguientes + // lo mismo puede ser escrito como: // let t = array[i]; array[i] = array[j]; array[j] = t [array[i], array[j]] = [array[j], array[i]]; } } ``` -Let's test it the same way: +Probémoslo de la misma manera: ```js run function shuffle(array) { @@ -89,7 +90,7 @@ function shuffle(array) { } } -// counts of appearances for all possible permutations +// conteo de apariciones para todas las permutaciones posibles let count = { '123': 0, '132': 0, @@ -105,13 +106,13 @@ for (let i = 0; i < 1000000; i++) { count[array.join('')]++; } -// show counts of all possible permutations +// muestra el conteo para todas las permutaciones posibles for (let key in count) { alert(`${key}: ${count[key]}`); } ``` -The example output: +La salida del ejemplo: ```js 123: 166693 @@ -122,6 +123,6 @@ The example output: 321: 166316 ``` -Looks good now: all permutations appear with the same probability. +Ahora sí se ve bien: todas las permutaciones aparecen con la misma probabilidad. -Also, performance-wise the Fisher-Yates algorithm is much better, there's no "sorting" overhead. +Además, en cuanto al rendimiento el algoritmo de Fisher-Yates es mucho mejor, no hay "ordenamiento" superpuesto. diff --git a/1-js/05-data-types/05-array-methods/9-shuffle/task.md b/1-js/05-data-types/05-array-methods/9-shuffle/task.md index 970c53417..912b7ee5b 100644 --- a/1-js/05-data-types/05-array-methods/9-shuffle/task.md +++ b/1-js/05-data-types/05-array-methods/9-shuffle/task.md @@ -2,11 +2,11 @@ importance: 3 --- -# Shuffle an array +# Barajar un array -Write the function `shuffle(array)` that shuffles (randomly reorders) elements of the array. +Escribe la función `shuffle(array)` que baraje (reordene de forma aleatoria) los elementos del array. -Multiple runs of `shuffle` may lead to different orders of elements. For instance: +Multiples ejecuciones de `shuffle` puede conducir a diferentes órdenes de elementos. Por ejemplo: ```js let arr = [1, 2, 3]; @@ -22,4 +22,4 @@ shuffle(arr); // ... ``` -All element orders should have an equal probability. For instance, `[1,2,3]` can be reordered as `[1,2,3]` or `[1,3,2]` or `[3,1,2]` etc, with equal probability of each case. +Todos los reordenamientos de elementos tienen que tener la misma probabilidad. Por ejemplo, `[1,2,3]` puede ser reordenado como `[1,2,3]` o `[1,3,2]` o `[3,1,2]` etc, con igual probabilidad en cada caso. diff --git a/1-js/05-data-types/05-array-methods/article.md b/1-js/05-data-types/05-array-methods/article.md index 301696440..501b648b7 100644 --- a/1-js/05-data-types/05-array-methods/article.md +++ b/1-js/05-data-types/05-array-methods/article.md @@ -1,111 +1,111 @@ -# Array methods +# Métodos con arrays -Arrays provide a lot of methods. To make things easier, in this chapter they are split into groups. +Los arrays (arreglos / matríces) cuentan con muchos métodos. Para hacer las cosas más sencillas, en este capítulo se encuentran divididos en dos partes. -## Add/remove items +## Agregar/remover elementos -We already know methods that add and remove items from the beginning or the end: +Ya conocemos algunos métodos que agregan o extraen elementos del inicio o final de un array: -- `arr.push(...items)` -- adds items to the end, -- `arr.pop()` -- extracts an item from the end, -- `arr.shift()` -- extracts an item from the beginning, -- `arr.unshift(...items)` -- adds items to the beginning. +- `arr.push(...items)` -- agrega elementos al final, +- `arr.pop()` -- extrae un elemento del final, +- `arr.shift()` -- extrae un elemento del inicio, +- `arr.unshift(...items)` -- agrega elementos al principio. -Here are a few others. +Veamos algunos métodos más. ### splice -How to delete an element from the array? +¿Cómo podemos borrar un elemento de un array? -The arrays are objects, so we can try to use `delete`: +Los arrays son objetos, por lo que podemos usar `delete`: ```js run -let arr = ["I", "go", "home"]; +let arr = ["voy", "a", "casa"]; -delete arr[1]; // remove "go" +delete arr[1]; // remueve "a" alert( arr[1] ); // undefined -// now arr = ["I", , "home"]; +// ahora arr = ["voy", , "casa"]; alert( arr.length ); // 3 ``` -The element was removed, but the array still has 3 elements, we can see that `arr.length == 3`. +El elemento fue removido pero el array todavía tiene 3 elementos, podemos comprobarlo en la línea `arr.length == 3`. -That's natural, because `delete obj.key` removes a value by the `key`. It's all it does. Fine for objects. But for arrays we usually want the rest of elements to shift and occupy the freed place. We expect to have a shorter array now. +Esto es porque `delete obj.key` borra el valor de `key`. Es todo lo que hace. Funciona bien para objetos pero para arrays usualmente lo que buscamos es que el resto de los elemetos se muevan y ocupen el lugar libre. Lo que esperamos es un array más corto. -So, special methods should be used. +Por lo tanto, necesitamos utilizar métodos especiales. -The [arr.splice(start)](mdn:js/Array/splice) method is a swiss army knife for arrays. It can do everything: insert, remove and replace elements. +El método [arr.splice(start)](mdn:js/Array/splice) funciona como una navaja suiza para arrays. Puede hacer todo: insertar, remover y remplazar elementos. -The syntax is: +La sintáxis es: ```js arr.splice(index[, deleteCount, elem1, ..., elemN]) ``` -It starts from the position `index`: removes `deleteCount` elements and then inserts `elem1, ..., elemN` at their place. Returns the array of removed elements. +Comienza en el índice `index`: remueve `deleteCount` elementos y luego inserta `elem1, ..., elemN` en su lugar devolviendo un array con los elementos removidos. -This method is easy to grasp by examples. +Este método es más fácil de entender con ejemplos. -Let's start with the deletion: +Empecemos removiendo elementos: ```js run -let arr = ["I", "study", "JavaScript"]; +let arr = ["Yo", "estudio", "JavaScript"]; *!* -arr.splice(1, 1); // from index 1 remove 1 element +arr.splice(1, 1); // desde el índice 1 remover 1 elemento */!* -alert( arr ); // ["I", "JavaScript"] +alert( arr ); // ["Yo", "JavaScript"] ``` -Easy, right? Starting from the index `1` it removed `1` element. +¿Fácil no? Empezando desde el índice `1` removió `1` elementos -In the next example we remove 3 elements and replace them with the other two: +En el próximo ejemplo removemos 3 elementos y los reemplazamos con otros 2: ```js run -let arr = [*!*"I", "study", "JavaScript",*/!* "right", "now"]; +let arr = [*!*"Yo", "estudio", "JavaScript",*/!* "ahora", "mismo"]; -// remove 3 first elements and replace them with another -arr.splice(0, 3, "Let's", "dance"); +// remueve los primeros 3 elementos y los reemplaza con otros +arr.splice(0, 3, "a", "bailar"); -alert( arr ) // now [*!*"Let's", "dance"*/!*, "right", "now"] +alert( arr ) // ahora [*!*"a", "bailar"*/!*, "ahora", "mismo"] ``` -Here we can see that `splice` returns the array of removed elements: +Acá podemos ver que `splice` devuelve un array con los elementos removidos: ```js run -let arr = [*!*"I", "study",*/!* "JavaScript", "right", "now"]; +let arr = [*!*"Yo", "estudio",*/!* "JavaScript", "ahora", "mismo"]; -// remove 2 first elements +// remueve los 2 primeros elementos let removed = arr.splice(0, 2); -alert( removed ); // "I", "study" <-- array of removed elements +alert( removed ); // "Yo", "estudio" <-- array con los elementos removidos ``` -The `splice` method is also able to insert the elements without any removals. For that we need to set `deleteCount` to `0`: +El método `splice` también es capaz de insertar elementos sin remover ningún otro. Para eso necesitamos establecer `deleteCount` en `0`: ```js run -let arr = ["I", "study", "JavaScript"]; +let arr = ["Yo", "estudio", "JavaScript"]; -// from index 2 -// delete 0 -// then insert "complex" and "language" -arr.splice(2, 0, "complex", "language"); +// desde el index 2 +// remover 0 +// después insertar "el", "complejo" y "language" +arr.splice(2, 0,"el", "complejo", "language"); -alert( arr ); // "I", "study", "complex", "language", "JavaScript" +alert( arr ); // "Yo", "estudio","el", "complejo", "language", "JavaScript" ``` -````smart header="Negative indexes allowed" -Here and in other array methods, negative indexes are allowed. They specify the position from the end of the array, like here: +````smart header="Los índices negativos están permitidos" +En este y en otros métodos de arrays, los índices negativos están permitidos. Estos índices indican la posición comenzando desde el final del array, de la siguiente manera: ```js run let arr = [1, 2, 5]; -// from index -1 (one step from the end) -// delete 0 elements, -// then insert 3 and 4 +// desde el index -1 (un lugar desde el final) +// remover 0 elementos, +// después insertar 3 y 4 arr.splice(-1, 0, 3, 4); alert( arr ); // 1,2,3,4,5 @@ -114,62 +114,62 @@ alert( arr ); // 1,2,3,4,5 ### slice -The method [arr.slice](mdn:js/Array/slice) is much simpler than similar-looking `arr.splice`. +El método [arr.slice](mdn:js/Array/slice) es mucho más simple que `arr.splice`. -The syntax is: +La sintáxis es: ```js -arr.slice([start], [end]) +arr.slice([principio], [final]) ``` -It returns a new array copying to it all items from index `start` to `end` (not including `end`). Both `start` and `end` can be negative, in that case position from array end is assumed. +Devuelve un nuevo array copiando en el mismo todos los elementos desde `principio` hasta `final` (sin incluir `final`). Ambos `principio` y `final` pueden ser negativos en cuyo caso si se incluye la posición final del array. -It's similar to a string method `str.slice`, but instead of substrings it makes subarrays. +Es similar al método para strings `str.slice`, pero en lugar de substrings genera subarrays. -For instance: +Por ejemplo: ```js run let arr = ["t", "e", "s", "t"]; -alert( arr.slice(1, 3) ); // e,s (copy from 1 to 3) +alert( arr.slice(1, 3) ); // e,s (copia desde 1 hasta 3) -alert( arr.slice(-2) ); // s,t (copy from -2 till the end) +alert( arr.slice(-2) ); // s,t (copia desde -2 hasta el final) ``` -We can also call it without arguments: `arr.slice()` creates a copy of `arr`. That's often used to obtain a copy for further transformations that should not affect the original array. +También podemos invocarlo sin argumentos: `arr.slice()` crea una copia de `arr`.Usualmente esto se utiliza para obtener una copia para futuras transformaciones sin afectar el array original. ### concat -The method [arr.concat](mdn:js/Array/concat) creates a new array that includes values from other arrays and additional items. +El método [arr.concat](mdn:js/Array/concat) crea un nuevo array que incluye valores de otros arrays y elementos adicionales. -The syntax is: +La sintaxis es: ```js arr.concat(arg1, arg2...) ``` -It accepts any number of arguments -- either arrays or values. +Este acepta cualquier número de argumentos --tanto arrays como valores. -The result is a new array containing items from `arr`, then `arg1`, `arg2` etc. +El resultado es un nuevo array que contiene elementos de `arr`, después `arg1`, `arg2` etc. -If an argument `argN` is an array, then all its elements are copied. Otherwise, the argument itself is copied. +Si un argumento `argN` es un array, entonces todos sus elementos son copiados. En otra palabras, el argumento en si es copiado. -For instance: +Por ejemplo: ```js run let arr = [1, 2]; -// create an array from: arr and [3,4] +// crea un array a partir de: arr y [3,4] alert( arr.concat([3, 4]) ); // 1,2,3,4 -// create an array from: arr and [3,4] and [5,6] +// crea un array a partir de: arr y [3,4] y [5,6] alert( arr.concat([3, 4], [5, 6]) ); // 1,2,3,4,5,6 -// create an array from: arr and [3,4], then add values 5 and 6 +// crea un array a partir de: arr y [3,4], luego agrega los valores 5 y 6 alert( arr.concat([3, 4], 5, 6) ); // 1,2,3,4,5,6 ``` -Normally, it only copies elements from arrays. Other objects, even if they look like arrays, are added as a whole: +Normalmente solo copia elementos desde arrays. Otros objetos, incluso si parecen arrays, son agregados como un todo: ```js run let arr = [1, 2]; @@ -182,7 +182,7 @@ let arrayLike = { alert( arr.concat(arrayLike) ); // 1,2,[object Object] ``` -...But if an array-like object has a special `Symbol.isConcatSpreadable` property, then it's treated as an array by `concat`: its elements are added instead: +...Pero si un objeto similar a un array tiene la propiedad especial `Symbol.isConcatSpreadable`, entonces es tratado como un array por `concat` y en lugar de ser añadido como un todo, solo son añadidos sus elementos. ```js run let arr = [1, 2]; @@ -199,25 +199,25 @@ let arrayLike = { alert( arr.concat(arrayLike) ); // 1,2,something,else ``` -## Iterate: forEach +## Iteración: forEach -The [arr.forEach](mdn:js/Array/forEach) method allows to run a function for every element of the array. +El método [arr.forEach](mdn:js/Array/forEach) permite ejecutar una función a cada elemento del array. -The syntax: +La sintaxis: ```js arr.forEach(function(item, index, array) { - // ... do something with item + // ... hacer algo con el elemento }); ``` -For instance, this shows each element of the array: +Por ejemplo, el siguiente código muestra cada elemento del array: ```js run -// for each element call alert +// para cada elemento ejecuta alert ["Bilbo", "Gandalf", "Nazgul"].forEach(alert); ``` -And this code is more elaborate about their positions in the target array: +Y este caso es más detallado acerca de la posición del elemento objetivo en el array: ```js run ["Bilbo", "Gandalf", "Nazgul"].forEach((item, index, array) => { @@ -225,22 +225,22 @@ And this code is more elaborate about their positions in the target array: }); ``` -The result of the function (if it returns any) is thrown away and ignored. +El resultado de la función (si es que lo hay) se descarta y se ignora. -## Searching in array +## Buscar dentro de un array -Now let's cover methods that search in an array. +Ahora vamos a ver métodos que buscan elementos dentro de un array. -### indexOf/lastIndexOf and includes +### indexOf/lastIndexOf e includes -The methods [arr.indexOf](mdn:js/Array/indexOf), [arr.lastIndexOf](mdn:js/Array/lastIndexOf) and [arr.includes](mdn:js/Array/includes) have the same syntax and do essentially the same as their string counterparts, but operate on items instead of characters: +Los métodos [arr.indexOf](mdn:js/Array/indexOf), [arr.lastIndexOf](mdn:js/Array/lastIndexOf) y [arr.includes](mdn:js/Array/includes) tienen la misma sintaxis y hacen básicamente lo mismo que sus contrapartes de strings, pero operan sobre elementos en lugar de caracteres: -- `arr.indexOf(item, from)` -- looks for `item` starting from index `from`, and returns the index where it was found, otherwise `-1`. -- `arr.lastIndexOf(item, from)` -- same, but looks for from right to left. -- `arr.includes(item, from)` -- looks for `item` starting from index `from`, returns `true` if found. +- `arr.indexOf(item, from)` -- busca `item` comenzando desde el index `from`, y devuelve el index donde fue encontrado, es decir `-1`. +- `arr.lastIndexOf(item, from)` -- igual que el anterior, pero busca de derecha a izquierda. +- `arr.includes(item, from)` -- busca `item` comenzando desde el índice `from`, devuelve `true` en caso de ser encontrado. -For instance: +Por ejemplo: ```js run let arr = [1, 0, false]; @@ -252,109 +252,109 @@ alert( arr.indexOf(null) ); // -1 alert( arr.includes(1) ); // true ``` -Note that the methods use `===` comparison. So, if we look for `false`, it finds exactly `false` and not the zero. +Tener en cuenta que el método usa comparación estricta (`===`). Por lo tanto, si buscamos `false`, encontrará exactamente `false` y no cero. -If we want to check for inclusion, and don't want to know the exact index, then `arr.includes` is preferred. +Si queremos comprobar si un elemento está incluído y no necesitamos saber su ubicación exacta, entonces es preferible usar `arr.includes` -Also, a very minor difference of `includes` is that it correctly handles `NaN`, unlike `indexOf/lastIndexOf`: +Además, una pequeña diferencia de `includes` es que puede manejar correctamente `NaN` a diferencia de `indexOf/lastIndexOf`: ```js run const arr = [NaN]; -alert( arr.indexOf(NaN) ); // -1 (should be 0, but === equality doesn't work for NaN) -alert( arr.includes(NaN) );// true (correct) +alert( arr.indexOf(NaN) ); // -1 (debería ser 0, pero la igualdad === no funciona para NaN) +alert( arr.includes(NaN) );// true ``` -### find and findIndex +### find y findIndex -Imagine we have an array of objects. How do we find an object with the specific condition? +Imaginemos que tenemos un array de objetos. ¿Cómo podríamos encontrar un objeto con una condición específica? -Here the [arr.find(fn)](mdn:js/Array/find) method comes in handy. +Para este tipo de casos es útil el método [arr.find(fn)](mdn:js/Array/find) -The syntax is: +La sintáxis es: ```js let result = arr.find(function(item, index, array) { - // if true is returned, item is returned and iteration is stopped - // for falsy scenario returns undefined + // si true es devuelto, se devuelve el item y la iteración se detiene + // para el caso en que sea false devuelve undefined }); ``` -The function is called for elements of the array, one after another: +La función es llamada para cada elemento del array, uno después del otro: -- `item` is the element. -- `index` is its index. -- `array` is the array itself. +- `item` es el elemento. +- `index` es su índice. +- `array` es el array mismo. -If it returns `true`, the search is stopped, the `item` is returned. If nothing found, `undefined` is returned. +Si devuelve `true`, la búsqueda se detiene y el `item` es devuelto. Si no encuentra nada, entonces devuelve `undefined`. -For example, we have an array of users, each with the fields `id` and `name`. Let's find the one with `id == 1`: +Por ejemplo, si tenemos un array de usuarios, cada uno con los campos `id` y `name`. Encontremos el elemento con `id == 1`: ```js run let users = [ - {id: 1, name: "John"}, - {id: 2, name: "Pete"}, - {id: 3, name: "Mary"} + {id: 1, name: "Celina"}, + {id: 2, name: "David"}, + {id: 3, name: "Federico"} ]; let user = users.find(item => item.id == 1); -alert(user.name); // John +alert(user.name); // Celina ``` -In real life arrays of objects is a common thing, so the `find` method is very useful. +En la vida real los arrays de objetos son bastante comúnes por lo que el método `find` resulta muy útil. -Note that in the example we provide to `find` the function `item => item.id == 1` with one argument. That's typical, other arguments of this function are rarely used. +Ten en cuenta que en el ejemplo anterior le pasamos a `find` la función `item => item.id == 1` con un argumento. Esto es lo más común, otros argumentos son raramente usados en esta función. -The [arr.findIndex](mdn:js/Array/findIndex) method is essentially the same, but it returns the index where the element was found instead of the element itself and `-1` is returned when nothing is found. +El método [arr.findIndex](mdn:js/Array/findIndex) es escencialmente lo mismo, pero devuelve el índice donde el elemento fue encontrado en lugar del elemento en sí y devuelve `-1` cuando no encuentra nada. ### filter -The `find` method looks for a single (first) element that makes the function return `true`. +El método `find` busca un único elemento (el primero) que haga a la función devolver `true`. -If there may be many, we can use [arr.filter(fn)](mdn:js/Array/filter). +Si existieran varios elementos que cumplen la condición, podemos usar [arr.filter(fn)](mdn:js/Array/filter). -The syntax is similar to `find`, but `filter` returns an array of all matching elements: +La sintaxis es similar a `find`, pero `filter` devuelve un array con todos los elementos encontrados: ```js let results = arr.filter(function(item, index, array) { - // if true item is pushed to results and the iteration continues - // returns empty array if nothing found + // si devuelve true, el elemento es ingresado al array y la iteración continua + // si nada es encontrado, devuelve un array vacío }); ``` -For instance: +Por ejemplo: ```js run let users = [ - {id: 1, name: "John"}, - {id: 2, name: "Pete"}, - {id: 3, name: "Mary"} + {id: 1, name: "Celina"}, + {id: 2, name: "David"}, + {id: 3, name: "Federico"} ]; -// returns array of the first two users +// devuelve un array con los dos primeros usuarios let someUsers = users.filter(item => item.id < 3); alert(someUsers.length); // 2 ``` -## Transform an array +## Transformar un array -Let's move on to methods that transform and reorder an array. +Pasamos ahora a los métodos que transforman y reordenan un array. ### map -The [arr.map](mdn:js/Array/map) method is one of the most useful and often used. +El método [arr.map](mdn:js/Array/map) es uno de los métodos más comunes y ampliamente usados. -It calls the function for each element of the array and returns the array of results. +Llama a la función para cada elemento del array y devuelve un array con los resultados. -The syntax is: +La sintaxis es: ```js let result = arr.map(function(item, index, array) { - // returns the new value instead of item + // devuelve el nuevo valor en lugar de item }); ``` -For instance, here we transform each element into its length: +Por ejemplo, acá transformamos cada elemento en el valor de su respectivo largo (lenght): ```js run let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length); @@ -363,41 +363,41 @@ alert(lengths); // 5,7,6 ### sort(fn) -The call to [arr.sort()](mdn:js/Array/sort) sorts the array *in place*, changing its element order. +Cuando usamos [arr.sort()](mdn:js/Array/sort), este ordena el propio array cambiando el orden de los elementos. -It also returns the sorted array, but the returned value is usually ignored, as `arr` itself is modified. +También devuelve un nuevo array ordenado pero este usualmente se ignora ya que `arr` en sí mismo es modificado. -For instance: +Por ejemplo: ```js run let arr = [ 1, 2, 15 ]; -// the method reorders the content of arr +// el método reordena el contenido de arr arr.sort(); alert( arr ); // *!*1, 15, 2*/!* ``` -Did you notice anything strange in the outcome? +¿Notas algo extraño en los valores de salida? -The order became `1, 15, 2`. Incorrect. But why? +Los elementos fueron reordenados a `1, 15, 2`. ¿Pero por qué pasa esto? -**The items are sorted as strings by default.** +**Los elementos son ordenados como strings (cadenas de caracteres) por defecto** -Literally, all elements are converted to strings for comparisons. For strings, lexicographic ordering is applied and indeed `"2" > "15"`. +Todos los elementos son literalmente convertidos a string para ser comparados. En el caso de strings se aplica el orden lexicográfico, por lo que efectivamente `"2" > "15"`. -To use our own sorting order, we need to supply a function as the argument of `arr.sort()`. +Para usar nuestro propio criterio de reordenamiento, necesitamos proporcionar una función como argumento de `arr.sort()`. -The function should compare two arbitrary values and return: +La función debe comparar dos valores arbitrarios y devolver el resultado: ```js function compare(a, b) { - if (a > b) return 1; // if the first value is greater than the second - if (a == b) return 0; // if values are equal - if (a < b) return -1; // if the first value is less than the second + if (a > b) return 1; // si el primer valor es mayor que el segundo + if (a == b) return 0; // si ambos valores son iguales + if (a < b) return -1; // si el primer valor es menor que el segundo } ``` -For instance, to sort as numbers: +Por ejemplo, para ordenar como números: ```js run function compareNumeric(a, b) { @@ -415,13 +415,13 @@ arr.sort(compareNumeric); alert(arr); // *!*1, 2, 15*/!* ``` -Now it works as intended. +Ahora sí funciona como esperábamos. -Let's step aside and think what's happening. The `arr` can be array of anything, right? It may contain numbers or strings or objects or whatever. We have a set of *some items*. To sort it, we need an *ordering function* that knows how to compare its elements. The default is a string order. +Demos un paso al costado un momento y pensemos que es lo que está pasando. El array `arr` puede ser un array de cualquier cosa, ¿no? Puede contener números, strings, objetos o lo que sea. Podemos decir que tenemos un conjunto de *ciertos items*. Para ordenarlos, necesitamos una *función de orden* que sepa cómo comparar los elementos. El orden por defecto es hacerlo como strings. -The `arr.sort(fn)` method implements a generic sorting algorithm. We don't need to care how it internally works (an optimized [quicksort](https://en.wikipedia.org/wiki/Quicksort) most of the time). It will walk the array, compare its elements using the provided function and reorder them, all we need is to provide the `fn` which does the comparison. +El método `arr.sort(fn)` implementa un algorito genérico de orden. No necesitamos preocuparnos de cómo funciona internamente (la mayoría de las veces es una forma optimizada del algoritmo [quicksort](https://es.wikipedia.org/wiki/Quicksort)). Este método va a recorrer el array, comparar sus elementos usando la función dada y, finalmente, reordenarlos. Todo los que necesitamos hacer es proveer la `fn` que realiza la comparación. -By the way, if we ever want to know which elements are compared -- nothing prevents from alerting them: +Por cierto, si alguna vez queremos saber qué elementos son comparados -- nada nos impide ejecutar alert() en ellos: ```js run [1, -2, 15, 2, 0, 8].sort(function(a, b) { @@ -429,12 +429,12 @@ By the way, if we ever want to know which elements are compared -- nothing preve }); ``` -The algorithm may compare an element with multiple others in the process, but it tries to make as few comparisons as possible. +El algoritmo puede comparar un elemento con muchos otros en el proceso, pero trata de hacer la menor cantidad de comparaciones posible. -````smart header="A comparison function may return any number" -Actually, a comparison function is only required to return a positive number to say "greater" and a negative number to say "less". +````smart header="Una función de comparación puede devolver cualquier número" +En realidad, una función de comparación solo es requerida para devolver un número positivo para "mayor" y uno negativo para "menor". -That allows to write shorter functions: +Esto nos permite escribir una función más corta: ```js run let arr = [ 1, 2, 15 ]; @@ -445,37 +445,37 @@ alert(arr); // *!*1, 2, 15*/!* ``` ```` -````smart header="Arrow functions for the best" -Remember [arrow functions](info:arrow-functions-basics)? We can use them here for neater sorting: +````smart header="Funciones arrow" +¿Recuerdas las [arrow functions](info:arrow-functions-basics)? Podemos usarlas en este caso para un ordenamiento más prolijo: ```js arr.sort( (a, b) => a - b ); ``` -This works exactly the same as the longer version above. +Esto funciona exactamente igual que la versión más larga de arriba. ```` -````smart header="Use `localeCompare` for strings" -Remember [strings](info:string#correct-comparisons) comparison algorithm? It compares letters by their codes by default. +````smart header="Usa `localeCompare` para strings" +¿Recuerdas el algoritmo de comparación [strings](info:string#correct-comparisons)? Compara letras por su código por defecto. -For many alphabets, it's better to use `str.localeCompare` method to correctly sort letters, such as `Ö`. +Para muchos alfabetos, es mejor usar el método `str.localeCompare` para ordenar correctamente letras como por ejemplo `Ö`. -For example, let's sort a few countries in German: +Por ejemplo, vamos a ordenar algunos países en alemán: ```js run -let countries = ['Österreich', 'Andorra', 'Vietnam']; +let paises = ['Österreich', 'Andorra', 'Vietnam']; -alert( countries.sort( (a, b) => a > b ? 1 : -1) ); // Andorra, Vietnam, Österreich (wrong) +alert( paises.sort( (a, b) => a > b ? 1 : -1) ); // Andorra, Vietnam, Österreich (incorrecto) -alert( countries.sort( (a, b) => a.localeCompare(b) ) ); // Andorra,Österreich,Vietnam (correct!) +alert( paises.sort( (a, b) => a.localeCompare(b) ) ); // Andorra,Österreich,Vietnam (¡correcto!) ``` ```` ### reverse -The method [arr.reverse](mdn:js/Array/reverse) reverses the order of elements in `arr`. +El método [arr.reverse](mdn:js/Array/reverse) revierte el orden de los elementos en `arr`. -For instance: +Por ejemplo: ```js run let arr = [1, 2, 3, 4, 5]; @@ -484,27 +484,27 @@ arr.reverse(); alert( arr ); // 5,4,3,2,1 ``` -It also returns the array `arr` after the reversal. +También devuelve el array `arr` después de revertir el orden. -### split and join +### split y join -Here's the situation from real life. We are writing a messaging app, and the person enters the comma-delimited list of receivers: `John, Pete, Mary`. But for us an array of names would be much more comfortable than a single string. How to get it? +Analicemos una situación de la vida real. Estamos programando una app de mensajería y y el usuario ingresa una lista de receptores delimitada por comas: `Celina, David, Federico`. Pero para nosotros un array sería mucho más práctico que una simple string. ¿Cómo podemos hacer para obtener un array? -The [str.split(delim)](mdn:js/String/split) method does exactly that. It splits the string into an array by the given delimiter `delim`. +El método [str.split(delim)](mdn:js/String/split) hace precisamente eso. Separa la string en un array siguiendo el delimitante dado `delim`. -In the example below, we split by a comma followed by space: +En el ejemplo de abajo, separamos por comas seguidas de espacio: ```js run -let names = 'Bilbo, Gandalf, Nazgul'; +let nombres = 'Bilbo, Gandalf, Nazgul'; -let arr = names.split(', '); +let arr = nombres.split(', '); for (let name of arr) { - alert( `A message to ${name}.` ); // A message to Bilbo (and other names) + alert( `Un mensaje para ${name}.` ); // Un mensaje para Bilbo (y los otros nombres) } ``` -The `split` method has an optional second numeric argument -- a limit on the array length. If it is provided, then the extra elements are ignored. In practice it is rarely used though: +El método `split` tiene un segundo argumento numérico opcional -- un límite en la extensión del array. Si se provee este argumento, entonces el resto de los elementos son ignorados. Sin embargo en la práctica rara vez se utiliza: ```js run let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', ', 2); @@ -512,8 +512,8 @@ let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', ', 2); alert(arr); // Bilbo, Gandalf ``` -````smart header="Split into letters" -The call to `split(s)` with an empty `s` would split the string into an array of letters: +````smart header="Separar en letras" +El llamado a `split(s)` con un `s` vacío separará el strign en un array de letras: ```js run let str = "test"; @@ -522,27 +522,27 @@ alert( str.split('') ); // t,e,s,t ``` ```` -The call [arr.join(glue)](mdn:js/Array/join) does the reverse to `split`. It creates a string of `arr` items joined by `glue` between them. +El llamado de [arr.join(glue)](mdn:js/Array/join) hace lo opuesto a `split`. Crea una string de `arr` elementos unidos con `glue` entre ellos. -For instance: +Por ejemplo: ```js run let arr = ['Bilbo', 'Gandalf', 'Nazgul']; -let str = arr.join(';'); // glue the array into a string using ; +let str = arr.join(';'); // une el array en una string usando ; alert( str ); // Bilbo;Gandalf;Nazgul ``` ### reduce/reduceRight -When we need to iterate over an array -- we can use `forEach`, `for` or `for..of`. +Cuando necesitamos iterar sobre un array -- podemos usar `forEach`, `for` or `for..of`. -When we need to iterate and return the data for each element -- we can use `map`. +Cuando necesitamos iterar y devolver un valor por cada elemento -- podemos usar `map`. -The methods [arr.reduce](mdn:js/Array/reduce) and [arr.reduceRight](mdn:js/Array/reduceRight) also belong to that breed, but are a little bit more intricate. They are used to calculate a single value based on the array. +Los métodos [arr.reduce](mdn:js/Array/reduce) y [arr.reduceRight](mdn:js/Array/reduceRight) también pertenecen a ese grupo de acciones pero son un poco más complejos. Se los utiliza para calcular un único valor a partir del array. -The syntax is: +La sintaxis es la siguiente: ```js let value = arr.reduce(function(accumulator, item, index, array) { @@ -550,24 +550,24 @@ let value = arr.reduce(function(accumulator, item, index, array) { }, [initial]); ``` -The function is applied to all array elements one after another and "carries on" its result to the next call. +La función es aplicada a todos los elementos del array uno detrás de otro y arrastra los resultados al próximo llamado. -Arguments: +Argumentos: -- `accumulator` -- is the result of the previous function call, equals `initial` the first time (if `initial` is provided). -- `item` -- is the current array item. -- `index` -- is its position. -- `array` -- is the array. +- `accumulator` -- es el resultado del llamado previo de la función, equivale a `initial` la primera vez (si `initial` es dado como argumento). +- `item` -- es el elemento actual del array. +- `index` -- es la posición. +- `array` -- es el array. -As function is applied, the result of the previous function call is passed to the next one as the first argument. +Mientras la función sea llamada, el resultado del llamado anterior se pasa al siguiente como primer argumento. -So, the first argument is essentially the accumulator that stores the combined result of all previous executions. And at the end it becomes the result of `reduce`. +Entonces, el primer argumento es el acumulador que almacena los resultados combinados de todas las veces anteriores en que se ejecutó y al final, se convierte en el resultado de `reduce`. -Sounds complicated? +¿Suena complicado? -The easiest way to grasp that is by example. +La forma más simple de entender algo es con un ejemplo. -Here we get a sum of an array in one line: +Acá tenemos la suma de un array en una línea: ```js run let arr = [1, 2, 3, 4, 5]; @@ -577,74 +577,74 @@ let result = arr.reduce((sum, current) => sum + current, 0); alert(result); // 15 ``` -The function passed to `reduce` uses only 2 arguments, that's typically enough. +La función pasada a `reduce` utiliza solo 2 argumentos, esto generalmente es suficiente. -Let's see the details of what's going on. +Veamos los detalles de lo que está pasando. -1. On the first run, `sum` is the `initial` value (the last argument of `reduce`), equals `0`, and `current` is the first array element, equals `1`. So the function result is `1`. -2. On the second run, `sum = 1`, we add the second array element (`2`) to it and return. -3. On the 3rd run, `sum = 3` and we add one more element to it, and so on... +1. En la primer pasada, `sum` es el valor `initial` (el último argumento de `reduce`), equivale a `0`, y `current` es el primer elemento de array, equivale a `1`. Entonces el resultado de la función es `1`. +2. En la segunda pasada, `sum = 1`, agregamos el segundo elemento del array (`2`) y devolvemos el valor. +3. En la tercer pasada, `sum = 3` y le agregamos un elemento más, y así sucesivamente... -The calculation flow: +El flujo de cálculos: ![](reduce.svg) -Or in the form of a table, where each row represents a function call on the next array element: +O en la forma de una tabla, donde cada fila representa un llamado a una función en el pŕoximo elemento del array: | |`sum`|`current`|result| |---|-----|---------|---------| -|the first call|`0`|`1`|`1`| -|the second call|`1`|`2`|`3`| -|the third call|`3`|`3`|`6`| -|the fourth call|`6`|`4`|`10`| -|the fifth call|`10`|`5`|`15`| +|primer llamado|`0`|`1`|`1`| +|segundo llamado|`1`|`2`|`3`| +|tercer llamado|`3`|`3`|`6`| +|cuarto llamado|`6`|`4`|`10`| +|quinto llamado|`10`|`5`|`15`| -Here we can clearly see how the result of the previous call becomes the first argument of the next one. +Acá podemos ver claramente como el resultado del llamado anterior se convierte en el primer argumento del llamado siguiente. -We also can omit the initial value: +También podemos omitir el valor inicial: ```js run let arr = [1, 2, 3, 4, 5]; -// removed initial value from reduce (no 0) +// valor inicial removido (no 0) let result = arr.reduce((sum, current) => sum + current); alert( result ); // 15 ``` -The result is the same. That's because if there's no initial, then `reduce` takes the first element of the array as the initial value and starts the iteration from the 2nd element. +El resultado es el mismo. Esto es porque en el caso de no haber valor inicial, `reduce` toma el primer elemento del array como valor inicial y comienza la iteración a partir del segundo elemento. -The calculation table is the same as above, minus the first row. +La tabla de cálculos es igual a la anterior menos la primer fila. -But such use requires an extreme care. If the array is empty, then `reduce` call without initial value gives an error. +Pero este tipo de uso requiere tener extremo cuidado. Si el array está vacío, entonces el llamado a `reduce` sin valor inicial devuelve error. -Here's an example: +Acá vemos un ejemplo: ```js run let arr = []; -// Error: Reduce of empty array with no initial value -// if the initial value existed, reduce would return it for the empty arr. +// Error: Reduce en un array vacío sin valor inicial +// si el valor inicial existe, reduce lo devuelve en el arr vacío. arr.reduce((sum, current) => sum + current); ``` -So it's advised to always specify the initial value. +Por lo tanto siempre se recomienda especificar un valor inicial. -The method [arr.reduceRight](mdn:js/Array/reduceRight) does the same, but goes from right to left. +El método [arr.reduceRight](mdn:js/Array/reduceRight) realiza lo mismo, pero va de derecha a izquierda. ## Array.isArray -Arrays do not form a separate language type. They are based on objects. +Los arrays no conforman un tipo diferente de lenguaje. Están basados en objetos. -So `typeof` does not help to distinguish a plain object from an array: +Por eso `typeof` no ayuda a distinguir un objeto de un array: ```js run alert(typeof {}); // object -alert(typeof []); // same +alert(typeof []); // object ``` -...But arrays are used so often that there's a special method for that: [Array.isArray(value)](mdn:js/Array/isArray). It returns `true` if the `value` is an array, and `false` otherwise. +...Pero los arrays son utilizados tan a menudo que tienen un método especial: [Array.isArray(value)](mdn:js/Array/isArray). Este devuelve `true` si el `valor` es un array y `false` si no lo es. ```js run alert(Array.isArray({})); // false @@ -652,25 +652,25 @@ alert(Array.isArray({})); // false alert(Array.isArray([])); // true ``` -## Most methods support "thisArg" +## La mayoría de los métodos aceptan "thisArg" -Almost all array methods that call functions -- like `find`, `filter`, `map`, with a notable exception of `sort`, accept an optional additional parameter `thisArg`. +Casi todos los métodos para arrays que realizan llamados a funciones -- como `find`, `filter`, `map`, con la notable excepción de `sort`, aceptan un parámetro opcional adicional `thisArg`. -That parameter is not explained in the sections above, because it's rarely used. But for completeness we have to cover it. +Ese parámetro no está explicado en la sección anterior porque es raramente usado. Pero para ser exhaustivos necesitamos verlo. -Here's the full syntax of these methods: +Esta es la sintaxis completa de este método: ```js arr.find(func, thisArg); arr.filter(func, thisArg); arr.map(func, thisArg); // ... -// thisArg is the optional last argument +// thisArg es el último argumento opcional ``` -The value of `thisArg` parameter becomes `this` for `func`. +EL valor del parámetro `thisArg` se convierte en `this` para `func`. -For example, here we use a method of `army` object as a filter, and `thisArg` passes the context: +Por ejemplo, acá usamos un método del objeto `army` como un filtro y `thisArg` da el contexto: ```js run let army = { @@ -689,7 +689,7 @@ let users = [ ]; *!* -// find users, for who army.canJoin returns true +// encuentra usuarios para los cuales army.canJoin devuelve true let soldiers = users.filter(army.canJoin, army); */!* @@ -698,58 +698,58 @@ alert(soldiers[0].age); // 20 alert(soldiers[1].age); // 23 ``` -If in the example above we used `users.filter(army.canJoin)`, then `army.canJoin` would be called as a standalone function, with `this=undefined`, thus leading to an instant error. +Si en el ejemplo anterior usamos `users.filter(army.canJoin)`, entonces `army.canJoin` puede ser llamada como una función independiente, con `this=undefined`, lo que puede llevar a un error instantáneo. -A call to `users.filter(army.canJoin, army)` can be replaced with `users.filter(user => army.canJoin(user))`, that does the same. The former is used more often, as it's a bit easier to understand for most people. +La llamada a `users.filter(army.canJoin, army)` puede ser reemplazada con `users.filter(user => army.canJoin(user))` que realiza lo mismo. La forma anterior se usa más a menudo, ya que es un poco más fácil de entender. -## Summary +## Resumen -A cheat sheet of array methods: +Veamos el ayudamemoria de métodos para arrays: -- To add/remove elements: - - `push(...items)` -- adds items to the end, - - `pop()` -- extracts an item from the end, - - `shift()` -- extracts an item from the beginning, - - `unshift(...items)` -- adds items to the beginning. - - `splice(pos, deleteCount, ...items)` -- at index `pos` delete `deleteCount` elements and insert `items`. - - `slice(start, end)` -- creates a new array, copies elements from position `start` till `end` (not inclusive) into it. - - `concat(...items)` -- returns a new array: copies all members of the current one and adds `items` to it. If any of `items` is an array, then its elements are taken. +- Para agregar/remover elementos: + - `push(...items)` -- agrega elementos al final, + - `pop()` -- extrae elementos del final, + - `shift()` -- extrae elementos del inicio, + - `unshift(...items)` -- agrega elementos al inicio. + - `splice(pos, deleteCount, ...items)` -- al índice `pos` borra `deleteCount` elementos e inserta `items`. + - `slice(start, end)` -- crea un nuevo array y copia elementos desde la posición `start` hasta `end` (no incluído) en el nuevo array. + - `concat(...items)` -- devuelve un nuevo array: copia todos los elementos del array actual y le agrega `items`. Si alguno de los `items` es un array, entonces su primer elemento es tomado -- To search among elements: - - `indexOf/lastIndexOf(item, pos)` -- look for `item` starting from position `pos`, return the index or `-1` if not found. - - `includes(value)` -- returns `true` if the array has `value`, otherwise `false`. - - `find/filter(func)` -- filter elements through the function, return first/all values that make it return `true`. - - `findIndex` is like `find`, but returns the index instead of a value. +- Para buscar entre elements: + - `indexOf/lastIndexOf(item, pos)` -- busca por `item` comenzando desde la posición `pos`, devolviendo el índice o `-1` si no se encuentra. + - `includes(value)` -- devuelve `true` si el array tiene `value`, sino `false`. + - `find/filter(func)` -- filtra elementos a través de la función, devuelve el primer/todos los valores que devuelven `true`. + - `findIndex` es similar a `find` pero devuelve el índice en lugar del valor. -- To iterate over elements: - - `forEach(func)` -- calls `func` for every element, does not return anything. +- Para iterar sobre elementos: + - `forEach(func)` -- llama la `func` para cada elemento, no devuelve nada. -- To transform the array: - - `map(func)` -- creates a new array from results of calling `func` for every element. - - `sort(func)` -- sorts the array in-place, then returns it. - - `reverse()` -- reverses the array in-place, then returns it. - - `split/join` -- convert a string to array and back. - - `reduce(func, initial)` -- calculate a single value over the array by calling `func` for each element and passing an intermediate result between the calls. +- Para transformar el array: + - `map(func)` -- crea un nuevo array a partir de los resultados de llamar a la `func` para cada elemento. + - `sort(func)` -- ordena el array y lo devuelve. + - `reverse()` -- ordena el array de forma inversa y lo devuelve. + - `split/join` -- convierte una cadena en un array y viceversa. + - `reduce(func, initial)` -- calcula un solo valor para todo el array llamando a la `func` para cada elemento y pasando un resultado intermedio entre cada llamada. -- Additionally: - - `Array.isArray(arr)` checks `arr` for being an array. +- Adicional: + - `Array.isArray(arr)` comprueba que `arr` sea un array. -Please note that methods `sort`, `reverse` and `splice` modify the array itself. +Por favor tener en cuenta que `sort`, `reverse` y `splice` modifican el propio array. -These methods are the most used ones, they cover 99% of use cases. But there are few others: +Estos métodos son los más utilizados y cubren el 99% de los casos. Pero existen algunos más: -- [arr.some(fn)](mdn:js/Array/some)/[arr.every(fn)](mdn:js/Array/every) checks the array. +- [arr.some(fn)](mdn:js/Array/some)/[arr.every(fn)](mdn:js/Array/every) comprueba el array. - The function `fn` is called on each element of the array similar to `map`. If any/all results are `true`, returns `true`, otherwise `false`. + La función `fn` es llamada para cada elemento del array de manera similar a `map`. Si alguno/todos los resultados son `true`, devuelve `true`, si no, `false`. -- [arr.fill(value, start, end)](mdn:js/Array/fill) -- fills the array with repeating `value` from index `start` to `end`. +- [arr.fill(value, start, end)](mdn:js/Array/fill) -- llena el array repitiendo `value` desde el índice `start` hasta `end`. -- [arr.copyWithin(target, start, end)](mdn:js/Array/copyWithin) -- copies its elements from position `start` till position `end` into *itself*, at position `target` (overwrites existing). +- [arr.copyWithin(target, start, end)](mdn:js/Array/copyWithin) -- copia sus elementos desde la posición `start` hasta la posición `end` en *si mismo*, a la posición `target` (reescribe lo existente). -For the full list, see the [manual](mdn:js/Array). +Para la lista completa, ver [manual](mdn:js/Array). -From the first sight it may seem that there are so many methods, quite difficult to remember. But actually that's much easier. +A primera vista puede parecer que hay demasiados métodos para aprender y un tanto difíciles de recordar. Pero con el tiempo se vuelve más fácil. -Look through the cheat sheet just to be aware of them. Then solve the tasks of this chapter to practice, so that you have experience with array methods. +Mira a lo largo del ayudamemoria para tener un conocimiento de ellos. Después realiza las prácticas de este capítulo, así ganas experiencia con los métodos para arrays. -Afterwards whenever you need to do something with an array, and you don't know how -- come here, look at the cheat sheet and find the right method. Examples will help you to write it correctly. Soon you'll automatically remember the methods, without specific efforts from your side. +Finalmente si en algún momento necesitas hacer algo con un array y no sabes cómo -- vuelve a esta página, mira el ayudamemoria y encuentra el método correcto. Los ejemplos te ayudarán a escribirlos correctamente y pronto los recordarás automáticamente y sin esfuerzo.