fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@@ -0,0 +1,29 @@
---
title: Add Elements to the End of an Array Using concat Instead of push
localeTitle: Agregue elementos al final de una matriz usando concat en lugar de empujar
---
## Agregue elementos al final de una matriz usando concat en lugar de empujar
Cuando el método de `push` agrega un nuevo elemento al final de la matriz original, el método `concat` crea una nueva matriz que contiene los elementos de la matriz original y el nuevo elemento. La matriz original sigue siendo la misma cuando se usa `concat` .
#### Enlaces relevantes:
* [Array.prototype.concat ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)
## Solución
```javascript
function nonMutatingPush(original, newItem) {
// Add your code below this line
return original.concat(newItem);
// Add your code above this line
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);
```

View File

@@ -0,0 +1,39 @@
---
title: Apply Functional Programming to Convert Strings to URL Slugs
localeTitle: Aplique programación funcional para convertir cadenas en slugs de URL
---
## Aplique programación funcional para convertir cadenas en slugs de URL
### Solución
```javascript
// the global variable
var globalTitle = "Winter Is Coming";
// Add your code below this line
function urlSlug(title) {
return title.split(/\W/).filter((obj)=>{
return obj !=='';
}).join('-').toLowerCase();
}
// Add your code above this line
var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"
```
### Solución alternativa
```javascript
// the global variable
var globalTitle = "Winter Is Coming";
// Add your code below this line
function urlSlug(title) {
return title.toLowerCase().trim().split(/\s+/).join('-');
}
// Add your code above this line
var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"
```

View File

@@ -0,0 +1,31 @@
---
title: Avoid Mutations and Side Effects Using Functional Programming
localeTitle: Evite las mutaciones y los efectos secundarios utilizando la programación funcional
---
## Evite las mutaciones y los efectos secundarios utilizando la programación funcional
### Explicación del problema
Rellene el código del `incrementer` función para que devuelva el valor de la variable global `fixedValue` incrementado en uno. `fixedValue` no debe cambiar, sin importar cuántas veces se `incrememter` la función `incrememter` .
### Sugerencia 1
Usar el operador de incremento ( `++` ) en el valor `fixedValue` cambiará el valor `fixedValue` , lo que significa que ya no hará referencia al mismo valor con el que fue asignado.
### Solución:
```javascript
// the global variable
var fixedValue = 4;
function incrementer () {
// Add your code below this line
return fixedValue + 1;
// Add your code above this line
}
var newValue = incrementer(); // Should equal 5
console.log(fixedValue); // Should print 4
```

View File

@@ -0,0 +1,35 @@
---
title: Combine an Array into a String Using the join Method
localeTitle: Combina una matriz en una cadena usando el método de unión
---
## Combina una matriz en una cadena usando el método de unión
### Explicación del problema
Use el método de `join` (entre otros) dentro de la función de `sentensify` para hacer una oración de las palabras en la cadena `str` . La función debe devolver una cadena. Por ejemplo, "I-like-Star-Wars" se convertiría a "Me gusta Star Wars". Para este desafío, no utilice el método de `replace` .
#### Enlaces relevantes:
* [Array.prototype.join ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join)
* [String.prototype.split ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)
* [Expresiones regulares](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)
### Hint1
Es posible que deba convertir la cadena a una matriz primero.
### Hint2
Es posible que necesite usar una expresión regular para dividir la cadena.
### Solución:
```javascript
function sentensify(str) {
// Add your code below this line
return str.split(/\W/).join(' ');
// Add your code above this line
}
sentensify("May-the-force-be-with-you");
```

View File

@@ -0,0 +1,24 @@
---
title: Combine Two Arrays Using the concat Method
localeTitle: Combina dos matrices usando el método concat
---
## Combina dos matrices usando el método concat
* El método concat se utiliza para unir dos o más matrices o cadenas.
* Este método no muta las matrices existentes, pero devuelve una nueva matriz.
## Solución
```javascript
function nonMutatingConcat(original, attach) {
// Add your code below this line
return original.concat(attach);
// Add your code above this line
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingConcat(first, second);
```

View File

@@ -0,0 +1,34 @@
---
title: Implement map on a Prototype
localeTitle: Implementar mapa en un prototipo
---
## Implementar mapa en un prototipo
Para resolver ESTE desafío usando la palabra clave esta es una clave.
Nos dará acceso al objeto que estamos llamando myMap.
Desde allí podemos usar el bucle forEach o for para agregar elementos a una matriz vacía ya declarada a medida que modificamos cada elemento con el método de devolución de llamada dado.
```javascript
// the global Array
var s = [23, 65, 98, 5];
Array.prototype.myMap = function(callback){
var newArray = [];
// Add your code below this line
this.forEach(a => newArray.push(callback(a)));
// Add your code above this line
return newArray;
};
var new_s = s.myMap(function(item){
return item * 2;
});
```
### Enlaces útiles
[esta. Javascript MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
[esta. Javascript W3Schools](https://www.w3schools.com/js/js_this.asp)

View File

@@ -0,0 +1,45 @@
---
title: Implement the filter Method on a Prototype
localeTitle: Implementar el método de filtro en un prototipo
---
## Implementar el método de filtro en un prototipo
```javascript
// the global Array
var s = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback){
var newArray = [];
// Add your code below this line
this.forEach(function(x) {
if (callback(x) == true) {
newArray.push(x);
}
})
// Add your code above this line
return newArray;
};
```
## Otra solución usando para bucear!
```javascript
Array.prototype.myFilter = function(callback){
var newArray = [];
// Add your code below this line
for (let i=0; i<this.length;i++){
if(callback(this[i])=== true ){
newArray.push(this[i]);
}
}
// Add your code above this line
return newArray;
};
var new_s = s.myFilter(function(item){
return item % 2 === 1;
});
```

View File

@@ -0,0 +1,11 @@
---
title: Functional Programming
localeTitle: Programación Funcional
---
## Programación Funcional
Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md) .
[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) .
#### Más información:

View File

@@ -0,0 +1,21 @@
---
title: Introduction to Currying and Partial Application
localeTitle: Introducción al curry y aplicación parcial.
---
## Introducción al curry y aplicación parcial.
### Solución
```javascript
function add(x) {
// Add your code below this line
return function(y) {
return function(z) {
return x + y + z;
}
}
// Add your code above this line
}
add(10)(20)(30);
```

View File

@@ -0,0 +1,48 @@
---
title: Learn About Functional Programming
localeTitle: Aprenda acerca de la programación funcional
---
## Aprenda acerca de la programación funcional
Una función tiene una entrada o un parámetro `const myFunc = (input) => { ...code to execute... }` . En este caso, la entrada es cuántas tazas de té se crearán.
### Método
Solo se debe cambiar una línea de código para pasar este desafío. La función `getTea()` debe llamarse y almacenarse en la variable `tea4TeamFCC` . Asegúrese de leer la función `getTea()` y entender exactamente lo que hace. La función toma en una variable - `numOfCups` . `teaCups[]` se elabora una matriz `teaCups[]` y se configura un bucle for para contar el número de tazas pasadas a la función. Luego, se empuja una nueva taza de té a la matriz en cada iteración del bucle for.
De este modo, se `getTea()` una matriz llena de la cantidad de tazas de té que originalmente se pasaron a la función `getTea()` .
### Solución
```javascript
/**
* A long process to prepare tea.
* @return {string} A cup of tea.
**/
const prepareTea = () => 'greenTea';
/**
* Get given number of cups of tea.
* @param {number} numOfCups Number of required cups of tea.
* @return {Array<string>} Given amount of tea cups.
**/
const getTea = (numOfCups) => {
const teaCups = [];
for(let cups = 1; cups <= numOfCups; cups += 1) {
const teaCup = prepareTea();
teaCups.push(teaCup);
}
return teaCups;
};
// Add your code below this line
const tea4TeamFCC = getTea(40); // :(
// Add your code above this line
console.log(tea4TeamFCC);
```

View File

@@ -0,0 +1,32 @@
---
title: Pass Arguments to Avoid External Dependence in a Function
localeTitle: Pasar argumentos para evitar la dependencia externa en una función
---
## Pasar argumentos para evitar la dependencia externa en una función
## Sugerencia: 1
Intente pasar el argumento para funcionar y devolver el valor incrementado de este argumento.
**¡Solución por delante!**
## Solución de código básico:
```javascript
// the global variable
var fixedValue = 4;
// Add your code below this line
function incrementer (value) {
return value + 1;
// Add your code above this line
}
var newValue = incrementer(fixedValue); // Should equal 5
console.log(fixedValue); // Should print 4
```
### Método
Este código proporcionará el mismo resultado que el último desafío, solo que esta vez pasaremos el valor `fixedValue` a la función como un parámetro.

View File

@@ -0,0 +1,46 @@
---
title: Refactor Global Variables Out of Functions
localeTitle: Refactorizar variables globales fuera de funciones
---
## Refactorizar variables globales fuera de funciones
* Si tiene problemas para cambiar la lista de libros, intente utilizar una copia de la matriz en sus funciones.
* Aquí hay más información sobre \[cómo JavaScript maneja los argumentos de la función\] (https://codeburst.io/javascript-passing-by-value-vs- reference -plicated-in-plain-english-8d00fd06a47c).
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":principiante:") Solución de código básico:
## Solución 1
```javascript
function add (arr, bookName) {
let newArr = [...arr]; // Copy the bookList array to a new array.
newArr.push(bookName); // Add bookName parameter to the end of the new array.
return newArr; // Return the new array.
}
function remove (arr, bookName) {
let newArr = [...arr]; // Copy the bookList array to a new array.
if (newArr.indexOf(bookName) >= 0) { // Check whether the bookName parameter is in new array.
/.
newArr.splice(newArr.indexOf(bookName), 1); // Remove the given paramater from the new array.
return newArr; // Return the new array.
}
}
```
## Solucion 2
```javascript
function add (list,bookName) {
return [...list, bookName];
}
function remove (list,bookName) {
if (list.indexOf(bookName) >= 0) {
return list.filter((item) => item !== bookName);
}
}
```

View File

@@ -0,0 +1,24 @@
---
title: Remove Elements from an Array Using slice Instead of splice
localeTitle: Eliminar elementos de una matriz usando una división en lugar de empalme
---
## Eliminar elementos de una matriz usando una división en lugar de empalme
* La diferencia entre el método de división y división es que el método de división no muta la matriz original, sino que devuelve una nueva.
* El método de división toma 2 dos argumentos para que los índices comiencen y terminen la división (el final no es inclusivo).
* Si no desea mutar la matriz original, puede usar el método de división.
## Solución
```javascript
function nonMutatingSplice(cities) {
// Add your code below this line
return cities.slice(0, 3);
// Add your code above this line
}
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);
```

View File

@@ -0,0 +1,24 @@
---
title: Return a Sorted Array Without Changing the Original Array
localeTitle: Devuelva una matriz ordenada sin cambiar la matriz original
---
## Devuelva una matriz ordenada sin cambiar la matriz original
### Método
En primer lugar, concatene la matriz tomada como parámetro a una nueva matriz vacía. Luego use el método `sort()` como se vio en el último desafío y cree una función para ordenar la nueva matriz en orden ascendente.
### Solución
```javascript
var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
// Add your code below this line
return [].concat(arr).sort(function(a, b) {
return a - b;
});
// Add your code above this line
}
nonMutatingSort(globalArray);
```

View File

@@ -0,0 +1,34 @@
---
title: Return Part of an Array Using the slice Method
localeTitle: Devolver parte de una matriz utilizando el método de corte
---
## Devolver parte de una matriz utilizando el método de corte
### Explicación del problema
Utilice el método de división en la función sliceArray para devolver parte de la matriz anim, dados los índices beginSlice y endSlice proporcionados. La función debe devolver una matriz.
### Método
La función se puede escribir simplemente escribiendo una línea de código: una declaración de devolución. Al igual que en el ejemplo dado, corte la matriz que la función toma como parámetro utilizando los parámetros `beginSlice` y `endSlice` como parámetros para el método `slice()` . Recuerda la estructura del método `slice()` :
```javascript
var arr = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
arr.slice([index-to-begin-slice] , [index-to-end-slice]);
```
### Solución
```javascript
function sliceArray(anim, beginSlice, endSlice) {
// Add your code below this line
return anim.slice(beginSlice, endSlice);
// Add your code above this line
}
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
sliceArray(inputAnim, 1, 3);
```
#### Enlaces relevantes:
* [Array.prototype.slice ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)

View File

@@ -0,0 +1,35 @@
---
title: Sort an Array Alphabetically using the sort Method
localeTitle: Ordena una matriz alfabéticamente usando el método de clasificación
---
## Ordena una matriz alfabéticamente usando el método de clasificación
### Método
En el ejemplo dado, vemos cómo escribir una función que devolverá una nueva matriz en orden alfabético inverso.
```javascript
function reverseAlpha(arr) {
return arr.sort(function(a, b) {
return a < b;
});
}
reverseAlpha(['l', 'h', 'z', 'b', 's']);
// Returns ['z', 's', 'l', 'h', 'b']
```
Usando esta lógica, simplemente realice una ingeniería inversa de la función para devolver una nueva matriz en orden alfabético.
### Solución
```javascript
function alphabeticalOrder(arr) {
// Add your code below this line
return arr.sort(function(a,b) {
return a > b;
});
// Add your code above this line
}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
```

View File

@@ -0,0 +1,23 @@
---
title: Split a String into an Array Using the split Method
localeTitle: Dividir una cadena en una matriz usando el método de división
---
## Dividir una cadena en una matriz usando el método de división
### Método
Simplemente divide la cadena para crear una nueva matriz de palabras.
Se puede utilizar una expresión regular simple para lograr este resultado.
### Solución
```javascript
function splitify(str) {
// Add your code below this line
return str.split(/\W/);
// Add your code above this line
}
splitify("Hello World,I-am code");
```

View File

@@ -0,0 +1,51 @@
---
title: Understand Functional Programming Terminology
localeTitle: Entender la terminología de programación funcional
---
## Entender la terminología de programación funcional
### Método
Al igual que en el último desafío, debe llamar al método `getTea` y almacenarlo en una variable. Solo que esta vez, tiene 2 variables para almacenar 2 conjuntos separados de datos. Verá que la función `getTea()` es la misma que antes, solo que ahora toma 2 parámetros separados. El primer parámetro es una función, por lo que necesitaremos pasar la función `prepareGreenTea()` o la función `prepareBlackTea()` , seguida del segundo parámetro `numOfCups` que se puede ingresar como un entero.
### Solución
En este ejercicio estamos asignando el resultado de una función de orden superior a las variables. Para hacer esto, llamamos a una función con una función de devolución de llamada como parámetro.
## Insinuación:
`javascript const basketOne = makeBasket(addFruit, 10)`
\## Solución:
\`\` \`javascript
/ \*\*
* Un largo proceso para preparar té verde.
* @return {string} Una taza de té verde. \*\* / const prepareGreenTea = () => 'greenTea';
/ \*\*
* Consigue un número dado de tazas de té.
* @param {function (): string} prepareTea El tipo de función de preparación de té.
* @param {número} numOfCups Número de tazas de té requeridas.
* @return {Array } Dada la cantidad de tazas de té. \*\* / const getTea = (prepareTea, numOfCups) => { const teaCups = \[\];
para (deja tazas = 1; tazas <= numOfCups; tazas + = 1) { const teaCup = prepareTea (); teaCups.push (teaCup); }
devolver tazas de té; };
// Añade tu código debajo de esta línea const tea4GreenTeamFCC = getTea (prepareGreenTea, 27); // :) const tea4BlackTeamFCC = getTea (prepareBlackTea, 13); // :) // Añade tu código encima de esta línea
console.log ( tea4GreenTeamFCC, tea4BlackTeamFCC );
\`\` \`
## Explicación del código:
En la solución anterior pasamos a las funciones `prepareGreenTea()` y `prepareBlackTea()` como parámetros o funciones de devolución de llamada para las funciones `getTea()` asignadas a nuestras dos variables constantes `tea4BlackTeamFCC` y `tea4GreenTeamFCC` . De esta manera, no se cambian las variables globales, y tenemos la opción de agregar un número ilimitado de diferentes opciones de métodos `prepareTea()` ya que es una función de devolución de llamada que se pasa a la función de orden superior de `getTea()` .

View File

@@ -0,0 +1,9 @@
---
title: Understand the Hazards of Using Imperative Code
localeTitle: Entender los peligros de usar el código imperativo
---
## Entender los peligros de usar el código imperativo
Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/functional-programming/understand-the-hazards-of-using-imperative-code/index.md) .
[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) .

View File

@@ -0,0 +1,43 @@
---
title: Use the every Method to Check that Every Element in an Array Meets a Criteria
localeTitle: Use cada método para verificar que cada elemento de una matriz cumple con los criterios
---
## Use cada método para verificar que cada elemento de una matriz cumple con los criterios
### Explicación del problema:
Use `every` método dentro de la función `checkPositive` para verificar si cada elemento en `arr` es positivo. La función debe devolver un valor booleano.
#### Enlaces relevantes:
* [Array.prototype.every ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every)
### Insinuación
No olvides `return` .
## Solución
```javascript
function checkPositive(arr) {
// Add your code below this line
return arr.every(val => val > 0);
// Add your code above this line
}
checkPositive([1, 2, 3, -4, 5]);
```
## Solución alternativa
```javascript
function checkPositive(arr) {
// Add your code below this line
return arr.every(function(value) {
return value > 0;
});
// Add your code above this line
}
checkPositive([1, 2, 3, -4, 5]);
```

View File

@@ -0,0 +1,22 @@
---
title: Use the filter method to extract data from an array
localeTitle: Utilice el método de filtro para extraer datos de una matriz
---
## Utilice el método de filtro para extraer datos de una matriz
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ": speech_balloon:") Sugerencia: 1
Este desafío se resuelve en 2 pasos. Primero, Array.prototype.filter se usa para filtrar la matriz de modo que quede con elementos que tienen imdbRating> 8.0. Después de eso, Array.prototype.map puede usarse para dar forma a la salida al formato deseado.
### Solución
```javascript
// Add your code below this line
var filteredList = watchList.map(function(e) {
return {title: e["Title"], rating: e["imdbRating"]}
}).filter((e) => e.rating >= 8);
console.log(filteredList);
```

View File

@@ -0,0 +1,27 @@
---
title: Use the map Method to Extract Data from an Array
localeTitle: Utilice el método de mapa para extraer datos de una matriz
---
## Utilice el método de mapa para extraer datos de una matriz
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ": speech_balloon:") Sugerencia: 1
array.prototype.map toma una función como entrada y devuelve una matriz. La matriz devuelta incluye elementos que son procesados por la función. Esta función toma elementos individuales como entrada.
## ¡Alerta de spoiler!
![señal de advertencia](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**¡Solución por delante!**
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ": rotando luz:") Solución de código intermedio:
```javascript
rating = watchList.map( (item) => ({"title":item["Title"], "rating":item["imdbRating"]}) );
```
\### Código Explicación: Usando la notación ES6, cada elemento de la matriz se procesa para extraer el título y la calificación. Se necesitan paréntesis para devolver un objeto.
#### Enlaces relevantes
* [Funciones de flecha](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)

View File

@@ -0,0 +1,130 @@
---
title: Use the reduce Method to Analyze Data
localeTitle: Utilice el método de reducción para analizar datos
---
## Utilice el método de reducción para analizar datos
```javascript
// the global variable
var watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
// Add your code below this line
var averageRating = watchList.filter(x => x.Director === "Christopher Nolan").map(x => Number(x.imdbRating)).reduce((x1, x2) => x1 + x2) / watchList.filter(x => x.Director === "Christopher Nolan").length;
// Add your code above this line
console.log(averageRating);
```

View File

@@ -0,0 +1,23 @@
---
title: Use the some Method to Check that Any Elements in an Array Meet a Criteria
localeTitle: Use el método para verificar que cualquier elemento de una matriz cumpla con los criterios
---
## Use el método para verificar que cualquier elemento de una matriz cumpla con los criterios
### Explicación del problema
Use algún método dentro de la función checkPositive para verificar si algún elemento en arr es positivo. La función `checkPositive` debe devolver un valor booleano.
#### Enlaces relevantes:
* [Array.prototype.some ()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)
### Solución:
```javascript
function checkPositive(arr) {
return arr.some((elem) => elem > 0);
}
checkPositive([1, 2, 3, -4, 5]);
```