chore(i8n,curriculum): processed translations (#41534)

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
This commit is contained in:
camperbot
2021-03-20 00:31:24 -06:00
committed by GitHub
parent 0d3158d4f4
commit 4cd40f23d1
22 changed files with 284 additions and 261 deletions

View File

@ -1,6 +1,6 @@
---
id: 587d7daa367417b2b2512b6b
title: Split a String into an Array Using the split Method
title: Divide una cadena en un arreglo utilizando el método "split"
challengeType: 1
forumTopicId: 18305
dashedName: split-a-string-into-an-array-using-the-split-method
@ -8,35 +8,35 @@ dashedName: split-a-string-into-an-array-using-the-split-method
# --description--
The `split` method splits a string into an array of strings. It takes an argument for the delimiter, which can be a character to use to break up the string or a regular expression. For example, if the delimiter is a space, you get an array of words, and if the delimiter is an empty string, you get an array of each character in the string.
El método `split` divide una cadena en un arreglo de cadenas. Se necesita un argumento para el delimitador, el cual puede ser un carácter para separar la cadena o una expresión regular. Por ejemplo, si el delimitador es un espacio, se obtiene un arreglo de palabras y si el delimitador es una cadena vacía, se obtiene un arreglo de cada carácter en la cadena.
Here are two examples that split one string by spaces, then another by digits using a regular expression:
Aquí hay dos ejemplos que dividen una cadena por espacios, luego otra por dígitos utilizando una expresión regular:
```js
var str = "Hello World";
var bySpace = str.split(" ");
// Sets bySpace to ["Hello", "World"]
var otherString = "How9are7you2today";
var byDigits = otherString.split(/\d/);
// Sets byDigits to ["How", "are", "you", "today"]
```
Since strings are immutable, the `split` method makes it easier to work with them.
`bySpace` tendrá el valor `["Hello", "World"]` y `byDigits` tendrá el valor `["How", "are", "you", "today"]`.
Dado que las cadenas son inmutables, el método `split` facilita el trabajo con ellas.
# --instructions--
Use the `split` method inside the `splitify` function to split `str` into an array of words. The function should return the array. Note that the words are not always separated by spaces, and the array should not contain punctuation.
Utiliza el método `split` dentro de la función `splitify` para dividir `str` en un arreglo de palabras. La función debe devolver un arreglo. Ten en cuenta que las palabras no siempre están separadas por espacios y que el arreglo no debe contener signos de puntuación.
# --hints--
Your code should use the `split` method.
Tu código debe usar el método `split`.
```js
assert(code.match(/\.split/g));
```
`splitify("Hello World,I-am code")` should return `["Hello", "World", "I", "am", "code"]`.
`splitify("Hello World,I-am code")` debe devolver `["Hello", "World", "I", "am", "code"]`.
```js
assert(
@ -45,7 +45,7 @@ assert(
);
```
`splitify("Earth-is-our home")` should return `["Earth", "is", "our", "home"]`.
`splitify("Earth-is-our home")` debe devolver `["Earth", "is", "our", "home"]`.
```js
assert(
@ -54,7 +54,7 @@ assert(
);
```
`splitify("This.is.a-sentence")` should return `["This", "is", "a", "sentence"]`.
`splitify("This.is.a-sentence")` debe devolver `["This", "is", "a", "sentence"]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b8e367417b2b2512b5c
title: Understand Functional Programming Terminology
title: Comprende la terminología de la programación funcional
challengeType: 1
forumTopicId: 301240
dashedName: understand-functional-programming-terminology
@ -8,47 +8,47 @@ dashedName: understand-functional-programming-terminology
# --description--
The FCC Team had a mood swing and now wants two types of tea: green tea and black tea. General Fact: Client mood swings are pretty common.
El equipo de FCC tuvo un cambio de humor y ahora quiere dos tipos de té: té verde y té negro. Hecho general: Los cambios del estado de ánimo de los clientes son bastante concurrentes.
With that information, we'll need to revisit the `getTea` function from last challenge to handle various tea requests. We can modify `getTea` to accept a function as a parameter to be able to change the type of tea it prepares. This makes `getTea` more flexible, and gives the programmer more control when client requests change.
Con esa información, tendremos que volver a visitar la función `getTea` del último desafío para manejar varias solicitudes de té. Podemos modificar `getTea` para aceptar una función como parámetro y así poder cambiar el tipo de té que prepara. Esto hace que `getTea` sea más flexible y le da al programador más control cuando las solicitudes del cliente cambian.
But first, let's cover some functional terminology:
Pero primero, cubramos alguna terminología de la programación funcional:
<dfn>Callbacks</dfn> are the functions that are slipped or passed into another function to decide the invocation of that function. You may have seen them passed to other methods, for example in `filter`, the callback function tells JavaScript the criteria for how to filter an array.
<dfn>Callbacks</dfn> son las funciones que se deslizan o pasan a otra función para decidir la invocación de esa función. Es posible que las hayas visto pasar a otros métodos, por ejemplo en `filter`, la función callback le dice a JavaScript los criterios para filtrar un arreglo.
Functions that can be assigned to a variable, passed into another function, or returned from another function just like any other normal value, are called <dfn>first class</dfn> functions. In JavaScript, all functions are first class functions.
Las funciones que pueden ser asignadas a una variable, pasadas a otra función o devueltas desde otra función como cualquier otro valor normal, se llaman funciones de <dfn>primera clase</dfn>. En JavaScript, todas las funciones son funciones de primera clase.
The functions that take a function as an argument, or return a function as a return value are called <dfn>higher order</dfn> functions.
Las funciones que toman una función como argumento o devuelven una función como valor de retorno se llaman <dfn>funciones de orden superior</dfn>.
When the functions are passed in to another function or returned from another function, then those functions which gets passed in or returned can be called a <dfn>lambda</dfn>.
Cuando las funciones son pasadas a otra función o devueltas desde otra función, entonces esas funciones que se pasan o devuelven pueden llamarse una <dfn>lambda</dfn>.
# --instructions--
Prepare 27 cups of green tea and 13 cups of black tea and store them in `tea4GreenTeamFCC` and `tea4BlackTeamFCC` variables, respectively. Note that the `getTea` function has been modified so it now takes a function as the first argument.
Prepara 27 tazas de té verde (green tea) y 13 tazas de té negro (black tea) y almacénalas en las variables `tea4GreenTeamFCC` y `tea4BlackTeamFCC`, respectivamente. Ten en cuenta que la función `getTea` ha sido modificada por lo que ahora recibe una función como primer argumento.
Note: The data (the number of cups of tea) is supplied as the last argument. We'll discuss this more in later lessons.
Nota: Los datos (el número de tazas de té) son suministrados como el último argumento. Discutiremos más sobre esto en lecciones posteriores.
# --hints--
The `tea4GreenTeamFCC` variable should hold 27 cups of green tea for the team.
La variable `tea4GreenTeamFCC` debe contener 27 tazas de té verde para el equipo.
```js
assert(tea4GreenTeamFCC.length === 27);
```
The `tea4GreenTeamFCC` variable should hold cups of green tea.
La variable `tea4GreenTeamFCC` debe contener tazas de té verde.
```js
assert(tea4GreenTeamFCC[0] === 'greenTea');
```
The `tea4BlackTeamFCC` variable should hold 13 cups of black tea.
La variable `tea4BlackTeamFCC` debe contener 13 tazas de té negro.
```js
assert(tea4BlackTeamFCC.length === 13);
```
The `tea4BlackTeamFCC` variable should hold cups of black tea.
La variable `tea4BlackTeamFCC` debe contener tazas de té negro.
```js
assert(tea4BlackTeamFCC[0] === 'blackTea');

View File

@ -1,6 +1,6 @@
---
id: 587d7b8e367417b2b2512b5d
title: Understand the Hazards of Using Imperative Code
title: Comprende los peligros de usar el código imperativo
challengeType: 1
forumTopicId: 301241
dashedName: understand-the-hazards-of-using-imperative-code
@ -8,31 +8,31 @@ dashedName: understand-the-hazards-of-using-imperative-code
# --description--
Functional programming is a good habit. It keeps your code easy to manage, and saves you from sneaky bugs. But before we get there, let's look at an imperative approach to programming to highlight where you may have issues.
La programación funcional es un buen hábito. Mantiene tu código fácil de manejar y evita que tengas errores incómodos. Pero antes de llegar allí, veamos un enfoque imperativo de la programación para destacar dónde pueden tener problemas.
In English (and many other languages), the imperative tense is used to give commands. Similarly, an imperative style in programming is one that gives the computer a set of statements to perform a task.
En inglés (y muchos otros idiomas), la tensión imperativa se utiliza para dar órdenes. De forma similar, un estilo imperativo en la programación es aquel que le da a la computadora un conjunto de sentencias para llevar a cabo una tarea.
Often the statements change the state of the program, like updating global variables. A classic example is writing a `for` loop that gives exact directions to iterate over the indices of an array.
A menudo las sentencias cambian el estado del programa, como actualizar variables globales. Un ejemplo clásico es escribir un bucle `for` que dé instrucciones exactas para iterar sobre los índices de un arreglo.
In contrast, functional programming is a form of declarative programming. You tell the computer what you want done by calling a method or function.
Por el contrario, la programación funcional es una forma de programación declarativa. Le dice al ordenador lo que quieres hacer llamando a un método o funcn.
JavaScript offers many predefined methods that handle common tasks so you don't need to write out how the computer should perform them. For example, instead of using the `for` loop mentioned above, you could call the `map` method which handles the details of iterating over an array. This helps to avoid semantic errors, like the "Off By One Errors" that were covered in the Debugging section.
JavaScript ofrece muchos métodos predefinidos que manejan tareas comunes para que no necesites escribir cómo debe ejecutarlas el equipo. Por ejemplo, en lugar de usar el bucle `for` mencionado anteriormente se podría llamar al método `map` que maneja los detalles de iteración sobre un array. Esto ayuda a evitar errores semánticos, como los "Off By One Errors" que fueron cubiertos en la sección Debugging.
Consider the scenario: you are browsing the web in your browser, and want to track the tabs you have opened. Let's try to model this using some simple object-oriented code.
Considere el escenario: está navegando por la web en su navegador y quiere rastrear las pestañas que ha abierto. Intentemos modelar esto con un código simple orientado a objetos.
A Window object is made up of tabs, and you usually have more than one Window open. The titles of each open site in each Window object is held in an array. After working in the browser (opening new tabs, merging windows, and closing tabs), you want to print the tabs that are still open. Closed tabs are removed from the array and new tabs (for simplicity) get added to the end of it.
Un objeto ventana está formado por pestañas y normalmente tienes más de una abierta. Los títulos de cada sitio abierto en cada objeto ventana se mantienen en un arreglo. Después de trabajar en el navegador (abriendo nuevas pestañas, combinando ventanas y cerrando pestañas), deseas imprimir las pestañas que todavía están abiertas. Las pestañas cerradas se eliminan de la matriz y las nuevas pestañas (por simplicidad) se añaden al final de la misma.
The code editor shows an implementation of this functionality with functions for `tabOpen()`, `tabClose()`, and `join()`. The array `tabs` is part of the Window object that stores the name of the open pages.
El editor de código muestra una implementación de esta funcionalidad con funciones para `tabOpen()`, `tabClose()`y `join()`. El array `tabs` es parte del objeto ventana que almacena el nombre de las páginas abiertas.
# --instructions--
Examine the code in the editor. It's using a method that has side effects in the program, causing incorrect behaviour. The final list of open tabs, stored in `finalTabs.tabs`, should be `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` but the list produced by the code is slightly different.
Examine el código en el editor. Está utilizando un método que tiene efectos secundarios en el programa, causando un comportamiento incorrecto. La lista final de pestañas abiertas, almacenadas en `finalTabs.tabs` deberia ser `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` pero la lista producida por el código es un poco diferente.
Change `Window.prototype.tabClose` so that it removes the correct tab.
Cambia `Window.prototype.tabClose` para que elimine la pestaña correcta.
# --hints--
`finalTabs.tabs` should be `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`
`finalTabs.tabs` deberia ser `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`
```js
assert.deepEqual(finalTabs.tabs, [

View File

@ -1,6 +1,6 @@
---
id: 587d7dab367417b2b2512b6e
title: Use the every Method to Check that Every Element in an Array Meets a Criteria
title: Usa el método "every" para comprobar que cada elemento de un arreglo atienda un criterio
challengeType: 1
forumTopicId: 301312
dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria
@ -8,43 +8,44 @@ dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a
# --description--
The `every` method works with arrays to check if *every* element passes a particular test. It returns a Boolean value - `true` if all values meet the criteria, `false` if not.
El método `every` funciona con arreglos para comprobar si *every element* pasa una prueba en particular. Devuelve un valor booleano - `true` si todos los valores cumplen los criterios, `false` si no.
For example, the following code would check if every element in the `numbers` array is less than 10:
Por ejemplo, el siguiente código comprobaría si cada elemento en el arreglo `numbers` es menor a 10:
```js
var numbers = [1, 5, 8, 0, 10, 11];
numbers.every(function(currentValue) {
return currentValue < 10;
});
// Returns false
```
El método `every` devolvería `false` aquí.
# --instructions--
Use the `every` method inside the `checkPositive` function to check if every element in `arr` is positive. The function should return a Boolean value.
Utiliza el método `every` dentro de la función `checkPositive` para comprobar si cada elemento en `arr` es positivo. La función debe devolver un valor booleano.
# --hints--
Your code should use the `every` method.
Tu código debe usar el método `every`.
```js
assert(code.match(/\.every/g));
```
`checkPositive([1, 2, 3, -4, 5])` should return `false`.
`checkPositive([1, 2, 3, -4, 5])` debe devolver `false`.
```js
assert.isFalse(checkPositive([1, 2, 3, -4, 5]));
```
`checkPositive([1, 2, 3, 4, 5])` should return `true`.
`checkPositive([1, 2, 3, 4, 5])` debe devolver `true`.
```js
assert.isTrue(checkPositive([1, 2, 3, 4, 5]));
```
`checkPositive([1, -2, 3, -4, 5])` should return `false`.
`checkPositive([1, -2, 3, -4, 5])` debe devolver `false`.
```js
assert.isFalse(checkPositive([1, -2, 3, -4, 5]));

View File

@ -1,6 +1,6 @@
---
id: 587d7b8f367417b2b2512b63
title: Use the filter Method to Extract Data from an Array
title: Usa el método de "filter" para extraer datos de un arreglo
challengeType: 1
forumTopicId: 18179
dashedName: use-the-filter-method-to-extract-data-from-an-array
@ -8,13 +8,13 @@ dashedName: use-the-filter-method-to-extract-data-from-an-array
# --description--
Another useful array function is `Array.prototype.filter()`, or simply `filter()`.
Otra función útil de los arreglos es `Array.prototype.filter()` o simplemente `filter()`.
`filter` calls a function on each element of an array and returns a new array containing only the elements for which that function returns `true`. In other words, it filters the array, based on the function passed to it. Like `map`, it does this without needing to modify the original array.
`filter` llama a una funcn en cada elemento de un arreglo y devuelve un nuevo arreglo que contiene solo los elementos por lo que esa función devuelve `true`. En otras palabras, filtra el arreglo, basándose en la función que se le pasa. Al igual que `map`, hace esto sin necesidad de modificar el arreglo original.
The callback function accepts three arguments. The first argument is the current element being processed. The second is the index of that element and the third is the array upon which the `filter` method was called.
La función callback acepta tres argumentos. El primer argumento es el elemento actual que se está procesando. El segundo es el índice de ese elemento y el tercero es el arreglo sobre el que se llamó al método `filter`.
See below for an example using the `filter` method on the `users` array to return a new array containing only the users under the age of 30. For simplicity, the example only uses the first argument of the callback.
A continuación se muestra un ejemplo en el que se utiliza el método `filter` en el arreglo `users` para devolver un nuevo arreglo que contiene sólo a los usuarios menores de 30 años. Para que sea más fácil, el ejemplo sólo utiliza el primer argumento del callback.
```js
const users = [
@ -24,16 +24,18 @@ const users = [
];
const usersUnder30 = users.filter(user => user.age < 30);
console.log(usersUnder30); // [ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ]
console.log(usersUnder30);
```
La consola muestra el valor `[ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ]`.
# --instructions--
The variable `watchList` holds an array of objects with information on several movies. Use a combination of `filter` and `map` on `watchList` to assign a new array of objects with only `title` and `rating` keys. The new array should only include objects where `imdbRating` is greater than or equal to 8.0. Note that the rating values are saved as strings in the object and you may need to convert them into numbers to perform mathematical operations on them.
La variable `watchList` contiene un arreglo de objetos con información sobre varias películas. Utiliza una combinación de `filter` y `map` en `watchList` para asignar un nuevo arreglo de objetos con solo `title` y `rating` claves. El nuevo arreglo solo debe incluir objetos donde `imdbRating` es mayor o igual a 8.0. Ten en cuenta que los valores `rating` se guardan como cadenas en el objeto y puedes necesitar convertirlos en números para realizar operaciones matemáticas en ellos.
# --hints--
The `watchList` variable should not change.
La variable `watchList` no debe cambiar.
```js
assert(
@ -41,19 +43,19 @@ assert(
);
```
Your code should use the `filter` method.
Tu código debe usar el método `filter`.
```js
assert(code.match(/\.filter/g));
```
Your code should not use a `for` loop.
El código no debe utilizar el bucle `for`.
```js
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
```
`filteredList` should equal `[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]`.
`filteredList` debe ser igual a `[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]`.
```js
assert.deepEqual(filteredList, [

View File

@ -1,6 +1,6 @@
---
id: 587d7b8f367417b2b2512b61
title: Use the map Method to Extract Data from an Array
title: Usa el método "map" para extraer datos de un arreglo
challengeType: 1
forumTopicId: 18214
dashedName: use-the-map-method-to-extract-data-from-an-array
@ -8,19 +8,19 @@ dashedName: use-the-map-method-to-extract-data-from-an-array
# --description--
So far we have learned to use pure functions to avoid side effects in a program. Also, we have seen the value in having a function only depend on its input arguments.
Hasta ahora hemos aprendido a utilizar funciones puras para evitar efectos secundarios en un programa. Además, hemos aprendido el valor de tener una función que solo depende de sus argumentos de entrada.
This is only the beginning. As its name suggests, functional programming is centered around a theory of functions.
Este es solo el principio. Como su nombre indica, la programación funcional se centra en una teoría de funciones.
It would make sense to be able to pass them as arguments to other functions, and return a function from another function. Functions are considered <dfn>first class objects</dfn> in JavaScript, which means they can be used like any other object. They can be saved in variables, stored in an object, or passed as function arguments.
Tendría sentido pasarlos como argumentos a otras funciones y devolver una función de otra función. Las funciones se consideran <dfn>first class objects</dfn> en JavaScript, lo que significa que pueden ser usados como cualquier otro objeto. Pueden guardarse en variables, almacenarse en un objeto o pasarse como argumentos de función.
Let's start with some simple array functions, which are methods on the array object prototype. In this exercise we are looking at `Array.prototype.map()`, or more simply `map`.
Empecemos con algunas funciones de arreglos simples, que son métodos en el prototipo de objetos del arreglo. En este ejercicio estamos utilizando `Array.prototype.map()` o más específicamente `map`.
The `map` method iterates over each item in an array and returns a new array containing the results of calling the callback function on each element. It does this without mutating the original array.
El método `map` iterará sobre cada elemento de un arreglo y devuelve un nuevo arreglo que contiene los resultados de llamar a la función callback en cada elemento. Esto lo hace sin mutar el arreglo original.
When the callback is used, it is passed three arguments. The first argument is the current element being processed. The second is the index of that element and the third is the array upon which the `map` method was called.
Cuando se utiliza el callback, se pasan tres argumentos. El primer argumento es el elemento actual que se está procesando. El segundo es el índice de ese elemento y el tercero es el arreglo al que se llamó el método `map`.
See below for an example using the `map` method on the `users` array to return a new array containing only the names of the users as elements. For simplicity, the example only uses the first argument of the callback.
A continuación se muestra un ejemplo con el método `map` en el arreglo `users` para devolver un nuevo arreglo que contiene solo los nombres de los usuarios como elementos. Para que sea más fácil, el ejemplo solo utiliza el primer argumento del callback.
```js
const users = [
@ -30,16 +30,18 @@ const users = [
];
const names = users.map(user => user.name);
console.log(names); // [ 'John', 'Amy', 'camperCat' ]
console.log(names);
```
La consola mostraría el valor `[ 'John', 'Amy', 'camperCat' ]`.
# --instructions--
The `watchList` array holds objects with information on several movies. Use `map` on `watchList` to assign a new array of objects with only `title` and `rating` keys to the `ratings` variable. The code in the editor currently uses a `for` loop to do this, so you should replace the loop functionality with your `map` expression.
El arreglo `watchList` contiene objetos con información sobre varias películas. Usa `map` en `watchList` para asignar un nuevo arreglo de objetos con solo `title` y `rating` claves a la variable `ratings`. El código en el editor utiliza actualmente un bucle `for` para hacer esto, por lo que debería reemplazar la funcionalidad del bucle con su expresión `map`.
# --hints--
The `watchList` variable should not change.
La variable `watchList` no debe cambiar.
```js
assert(
@ -47,19 +49,19 @@ assert(
);
```
Your code should not use a `for` loop.
Tu código no debe usar un bucle `for`.
```js
assert(!__helpers.removeJSComments(code).match(/for\s*?\([\s\S]*?\)/));
```
Your code should use the `map` method.
Tu código debe usar el método `map`.
```js
assert(code.match(/\.map/g));
```
`ratings` should equal `[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]`.
`ratings` debe ser igual a `[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]`.
```js
assert.deepEqual(ratings, [

View File

@ -1,6 +1,6 @@
---
id: 587d7da9367417b2b2512b68
title: Use the reduce Method to Analyze Data
title: Utiliza el método "reduce" para analizar datos
challengeType: 1
forumTopicId: 301313
dashedName: use-the-reduce-method-to-analyze-data
@ -8,15 +8,15 @@ dashedName: use-the-reduce-method-to-analyze-data
# --description--
`Array.prototype.reduce()`, or simply `reduce()`, is the most general of all array operations in JavaScript. You can solve almost any array processing problem using the `reduce` method.
`Array.prototype.reduce()` o simplemente `reduce()` es la operación más común de todas para arreglos en JavaScript. Se puede resolver casi cualquier problema de procesamiento de arreglos utilizando el método `reduce`.
The `reduce` method allows for more general forms of array processing, and it's possible to show that both `filter` and `map` can be derived as special applications of `reduce`. The `reduce` method iterates over each item in an array and returns a single value (i.e. string, number, object, array). This is achieved via a callback function that is called on each iteration.
El método `reduce` permite formas más generales de procesamiento de arreglos y es posible mostrar que tanto `filter` como `map` pueden derivarse como aplicaciones especiales de `reduce`. El método `reduce` itera sobre cada elemento del arreglo y devuelve un solo valor (por ejemplo una cadena, número, objeto, arreglo). Esto se consigue mediante una función de callback que se llama en cada iteración.
The callback function accepts four arguments. The first argument is known as the accumulator, which gets assigned the return value of the callback function from the previous iteration, the second is the current element being processed, the third is the index of that element and the fourth is the array upon which `reduce` is called.
La función callback acepta cuatro argumentos. El primer argumento se conoce como acumulador, que recibe el valor retornado de la función callback de la iteración anterior, el segundo es el elemento actual que se está procesando, el tercero es el índice de ese elemento y el cuarto es el arreglo sobre el que se llama a la función `reduce`.
In addition to the callback function, `reduce` has an additional parameter which takes an initial value for the accumulator. If this second parameter is not used, then the first iteration is skipped and the second iteration gets passed the first element of the array as the accumulator.
Además de la función callback, `reduce` tiene un parámetro adicional que toma un valor inicial para el acumulador. Si este segundo parámetro no se utiliza, entonces la primera iteración se omite y la segunda se pasa por el primer elemento del arreglo como acumulador.
See below for an example using `reduce` on the `users` array to return the sum of all the users' ages. For simplicity, the example only uses the first and second arguments.
Mira a continuación un ejemplo con `reduce` en el arreglo `users` para devolver la suma de todas las edades de los usuarios. Para hacerlo más fácil, el ejemplo sólo utiliza el primer y segundo argumento.
```js
const users = [
@ -26,10 +26,12 @@ const users = [
];
const sumOfAges = users.reduce((sum, user) => sum + user.age, 0);
console.log(sumOfAges); // 64
console.log(sumOfAges);
```
In another example, see how an object can be returned containing the names of the users as properties with their ages as values.
La consola mostrará el valor `64`.
En otro ejemplo, se puede observar cómo un objeto puede ser devuelto con los nombres de los usuarios como propiedades con las edades como valores.
```js
const users = [
@ -42,16 +44,18 @@ const usersObj = users.reduce((obj, user) => {
obj[user.name] = user.age;
return obj;
}, {});
console.log(usersObj); // { John: 34, Amy: 20, camperCat: 10 }
console.log(usersObj);
```
La consola mostrará el valor `{ John: 34, Amy: 20, camperCat: 10 }`.
# --instructions--
The variable `watchList` holds an array of objects with information on several movies. Use `reduce` to find the average IMDB rating of the movies **directed by Christopher Nolan**. Recall from prior challenges how to `filter` data and `map` over it to pull what you need. You may need to create other variables, and return the average rating from `getRating` function. Note that the rating values are saved as strings in the object and need to be converted into numbers before they are used in any mathematical operations.
La variable `watchList` contiene un arreglo de objetos con información sobre varias películas. Utiliza `reduce` para encontrar la calificación media en IMDB de las películas dirigidas por `Christopher Nolan`. Recuerda de desafíos anteriores filtrar (`filter`) los datos y mapear (`map`) sobre ellos para extraer lo que necesitas. Puede que necesites crear otras variables y devolver la calificación media con la función `getRating`. Ten en cuenta que los valores de calificación se guardan como cadenas en el objeto y necesitan ser convertidos en números antes de ser utilizados en cualquier operación matemática.
# --hints--
The `watchList` variable should not change.
La variable `watchList` no debe cambiar.
```js
assert(
@ -59,25 +63,25 @@ assert(
);
```
Your code should use the `reduce` method.
Tu código debe utilizar el método `reduce`.
```js
assert(code.match(/\.reduce/g));
```
The `getRating(watchList)` should equal 8.675.
`getRating(watchList)` debe ser igual a 8.675.
```js
assert(getRating(watchList) === 8.675);
```
Your code should not use a `for` loop.
Tu código no debe usar un bucle `for`.
```js
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
```
Your code should return correct output after modifying the `watchList` object.
Tu código debe devolver el resultado correcto después de modificar el objeto `watchList`.
```js
assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55);

View File

@ -1,6 +1,6 @@
---
id: 587d7dab367417b2b2512b6f
title: Use the some Method to Check that Any Elements in an Array Meet a Criteria
title: Usa el método "some" para comprobar si algún elemento en un arreglo cumple un criterio
challengeType: 1
forumTopicId: 301314
dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria
@ -8,43 +8,44 @@ dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-cr
# --description--
The `some` method works with arrays to check if *any* element passes a particular test. It returns a Boolean value - `true` if any of the values meet the criteria, `false` if not.
El método `some` funciona con arreglos para comprobar si *algún* elemento pasa una prueba en particular. Devuelve un valor booleano `true` si alguno de los valores cumple el criterio, `false` si no.
For example, the following code would check if any element in the `numbers` array is less than 10:
Por ejemplo, el siguiente código comprobará si algún elemento en el arreglo `numbers` es menor que 10:
```js
var numbers = [10, 50, 8, 220, 110, 11];
numbers.some(function(currentValue) {
return currentValue < 10;
});
// Returns true
```
El método `some` devolverá `true`.
# --instructions--
Use the `some` method inside the `checkPositive` function to check if any element in `arr` is positive. The function should return a Boolean value.
Utiliza el método `some` dentro de la función `checkPositive` para comprobar si algún elemento en `arr` es positivo. La función debe devolver un valor booleano.
# --hints--
Your code should use the `some` method.
Tu código debe usar el método `some`.
```js
assert(code.match(/\.some/g));
```
`checkPositive([1, 2, 3, -4, 5])` should return `true`.
`checkPositive([1, 2, 3, -4, 5])` debe devolver `true`.
```js
assert(checkPositive([1, 2, 3, -4, 5]));
```
`checkPositive([1, 2, 3, 4, 5])` should return `true`.
`checkPositive([1, 2, 3, 4, 5])` debe devolver `true`.
```js
assert(checkPositive([1, 2, 3, 4, 5]));
```
`checkPositive([-1, -2, -3, -4, -5])` should return `false`.
`checkPositive([-1, -2, -3, -4, -5])` debe devolver `false`.
```js
assert(!checkPositive([-1, -2, -3, -4, -5]));