chore(i8n,learn): processed translations
This commit is contained in:
committed by
Mrugesh Mohapatra
parent
15047f2d90
commit
e5c44a3ae5
@ -0,0 +1,88 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b67
|
||||
title: Add Elements to the End of an Array Using concat Instead of push
|
||||
challengeType: 1
|
||||
forumTopicId: 301226
|
||||
dashedName: add-elements-to-the-end-of-an-array-using-concat-instead-of-push
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Functional programming is all about creating and using non-mutating functions.
|
||||
|
||||
The last challenge introduced the `concat` method as a way to combine arrays into a new one without mutating the original arrays. Compare `concat` to the `push` method. `Push` adds an item to the end of the same array it is called on, which mutates that array. Here's an example:
|
||||
|
||||
```js
|
||||
var arr = [1, 2, 3];
|
||||
arr.push([4, 5, 6]);
|
||||
// arr is changed to [1, 2, 3, [4, 5, 6]]
|
||||
// Not the functional programming way
|
||||
```
|
||||
|
||||
`Concat` offers a way to add new items to the end of an array without any mutating side effects.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `nonMutatingPush` function so it uses `concat` to add `newItem` to the end of `original` instead of `push`. The function should return an array.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `concat` method.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.concat/g));
|
||||
```
|
||||
|
||||
Your code should not use the `push` method.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?push/g));
|
||||
```
|
||||
|
||||
The `first` array should not change.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
|
||||
```
|
||||
|
||||
The `second` array should not change.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
|
||||
```
|
||||
|
||||
`nonMutatingPush([1, 2, 3], [4, 5])` should return `[1, 2, 3, 4, 5]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) ===
|
||||
JSON.stringify([1, 2, 3, 4, 5])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function nonMutatingPush(original, newItem) {
|
||||
// Only change code below this line
|
||||
return original.push(newItem);
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
var first = [1, 2, 3];
|
||||
var second = [4, 5];
|
||||
nonMutatingPush(first, second);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function nonMutatingPush(original, newItem) {
|
||||
return original.concat(newItem);
|
||||
}
|
||||
var first = [1, 2, 3];
|
||||
var second = [4, 5];
|
||||
nonMutatingPush(first, second);
|
||||
```
|
@ -0,0 +1,84 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6d
|
||||
title: Apply Functional Programming to Convert Strings to URL Slugs
|
||||
challengeType: 1
|
||||
forumTopicId: 301227
|
||||
dashedName: apply-functional-programming-to-convert-strings-to-url-slugs
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The last several challenges covered a number of useful array and string methods that follow functional programming principles. We've also learned about `reduce`, which is a powerful method used to reduce problems to simpler forms. From computing averages to sorting, any array operation can be achieved by applying it. Recall that `map` and `filter` are special cases of `reduce`.
|
||||
|
||||
Let's combine what we've learned to solve a practical problem.
|
||||
|
||||
Many content management sites (CMS) have the titles of a post added to part of the URL for simple bookmarking purposes. For example, if you write a Medium post titled "Stop Using Reduce", it's likely the URL would have some form of the title string in it (".../stop-using-reduce"). You may have already noticed this on the freeCodeCamp site.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fill in the `urlSlug` function so it converts a string `title` and returns the hyphenated version for the URL. You can use any of the methods covered in this section, and don't use `replace`. Here are the requirements:
|
||||
|
||||
The input is a string with spaces and title-cased words
|
||||
|
||||
The output is a string with the spaces between words replaced by a hyphen (`-`)
|
||||
|
||||
The output should be all lower-cased letters
|
||||
|
||||
The output should not have any spaces
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should not use the `replace` method for this challenge.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?replace/g));
|
||||
```
|
||||
|
||||
`urlSlug("Winter Is Coming")` should return `"winter-is-coming"`.
|
||||
|
||||
```js
|
||||
assert(urlSlug('Winter Is Coming') === 'winter-is-coming');
|
||||
```
|
||||
|
||||
`urlSlug(" Winter Is Coming")` should return `"winter-is-coming"`.
|
||||
|
||||
```js
|
||||
assert(urlSlug(' Winter Is Coming') === 'winter-is-coming');
|
||||
```
|
||||
|
||||
`urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")` should return `"a-mind-needs-books-like-a-sword-needs-a-whetstone"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
urlSlug('A Mind Needs Books Like A Sword Needs A Whetstone') ===
|
||||
'a-mind-needs-books-like-a-sword-needs-a-whetstone'
|
||||
);
|
||||
```
|
||||
|
||||
`urlSlug("Hold The Door")` should return `"hold-the-door"`.
|
||||
|
||||
```js
|
||||
assert(urlSlug('Hold The Door') === 'hold-the-door');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
function urlSlug(title) {
|
||||
|
||||
|
||||
}
|
||||
// Only change code above this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// Only change code below this line
|
||||
function urlSlug(title) {
|
||||
return title.trim().split(/\s+/).join("-").toLowerCase();
|
||||
}
|
||||
```
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5e
|
||||
title: Avoid Mutations and Side Effects Using Functional Programming
|
||||
challengeType: 1
|
||||
forumTopicId: 301228
|
||||
dashedName: avoid-mutations-and-side-effects-using-functional-programming
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
If you haven't already figured it out, the issue in the previous challenge was with the `splice` call in the `tabClose()` function. Unfortunately, `splice` changes the original array it is called on, so the second call to it used a modified array, and gave unexpected results.
|
||||
|
||||
This is a small example of a much larger pattern - you call a function on a variable, array, or an object, and the function changes the variable or something in the object.
|
||||
|
||||
One of the core principles of functional programming is to not change things. Changes lead to bugs. It's easier to prevent bugs knowing that your functions don't change anything, including the function arguments or any global variable.
|
||||
|
||||
The previous example didn't have any complicated operations but the `splice` method changed the original array, and resulted in a bug.
|
||||
|
||||
Recall that in functional programming, changing or altering things is called <dfn>mutation</dfn>, and the outcome is called a <dfn>side effect</dfn>. A function, ideally, should be a <dfn>pure function</dfn>, meaning that it does not cause any side effects.
|
||||
|
||||
Let's try to master this discipline and not alter any variable or object in our code.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fill in the code for the function `incrementer` so it returns the value of the global variable `fixedValue` increased by one.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your function `incrementer` should not change the value of `fixedValue` (which is `4`).
|
||||
|
||||
```js
|
||||
incrementer();
|
||||
assert(fixedValue === 4);
|
||||
```
|
||||
|
||||
Your `incrementer` function should return a value that is one larger than the `fixedValue` value.
|
||||
|
||||
```js
|
||||
const __newValue = incrementer();
|
||||
assert(__newValue === 5);
|
||||
```
|
||||
|
||||
Your `incrementer` function should return a value based on the global `fixedValue` variable value.
|
||||
|
||||
```js
|
||||
(function () {
|
||||
fixedValue = 10;
|
||||
const newValue = incrementer();
|
||||
assert(fixedValue === 10 && newValue === 11);
|
||||
fixedValue = 4;
|
||||
})();
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var fixedValue = 4;
|
||||
|
||||
function incrementer () {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var fixedValue = 4
|
||||
|
||||
function incrementer() {
|
||||
return fixedValue + 1
|
||||
}
|
||||
```
|
@ -0,0 +1,90 @@
|
||||
---
|
||||
id: 587d7daa367417b2b2512b6c
|
||||
title: Combine an Array into a String Using the join Method
|
||||
challengeType: 1
|
||||
forumTopicId: 18221
|
||||
dashedName: combine-an-array-into-a-string-using-the-join-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The `join` method is used to join the elements of an array together to create a string. It takes an argument for the delimiter that is used to separate the array elements in the string.
|
||||
|
||||
Here's an example:
|
||||
|
||||
```js
|
||||
var arr = ["Hello", "World"];
|
||||
var str = arr.join(" ");
|
||||
// Sets str to "Hello World"
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `join` method (among others) inside the `sentensify` function to make a sentence from the words in the string `str`. The function should return a string. For example, "I-like-Star-Wars" would be converted to "I like Star Wars". For this challenge, do not use the `replace` method.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `join` method.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.join/g));
|
||||
```
|
||||
|
||||
Your code should not use the `replace` method.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?replace/g));
|
||||
```
|
||||
|
||||
`sentensify("May-the-force-be-with-you")` should return a string.
|
||||
|
||||
```js
|
||||
assert(typeof sentensify('May-the-force-be-with-you') === 'string');
|
||||
```
|
||||
|
||||
`sentensify("May-the-force-be-with-you")` should return `"May the force be with you"`.
|
||||
|
||||
```js
|
||||
assert(sentensify('May-the-force-be-with-you') === 'May the force be with you');
|
||||
```
|
||||
|
||||
`sentensify("The.force.is.strong.with.this.one")` should return `"The force is strong with this one"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
sentensify('The.force.is.strong.with.this.one') ===
|
||||
'The force is strong with this one'
|
||||
);
|
||||
```
|
||||
|
||||
`sentensify("There,has,been,an,awakening")` should return `"There has been an awakening"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
sentensify('There,has,been,an,awakening') === 'There has been an awakening'
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sentensify(str) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
sentensify("May-the-force-be-with-you");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sentensify(str) {
|
||||
// Only change code below this line
|
||||
return str.split(/\W/).join(' ');
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
@ -0,0 +1,78 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b66
|
||||
title: Combine Two Arrays Using the concat Method
|
||||
challengeType: 1
|
||||
forumTopicId: 301229
|
||||
dashedName: combine-two-arrays-using-the-concat-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>Concatenation</dfn> means to join items end to end. JavaScript offers the `concat` method for both strings and arrays that work in the same way. For arrays, the method is called on one, then another array is provided as the argument to `concat`, which is added to the end of the first array. It returns a new array and does not mutate either of the original arrays. Here's an example:
|
||||
|
||||
```js
|
||||
[1, 2, 3].concat([4, 5, 6]);
|
||||
// Returns a new array [1, 2, 3, 4, 5, 6]
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `concat` method in the `nonMutatingConcat` function to concatenate `attach` to the end of `original`. The function should return the concatenated array.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `concat` method.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.concat/g));
|
||||
```
|
||||
|
||||
The `first` array should not change.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
|
||||
```
|
||||
|
||||
The `second` array should not change.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
|
||||
```
|
||||
|
||||
`nonMutatingConcat([1, 2, 3], [4, 5])` should return `[1, 2, 3, 4, 5]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(nonMutatingConcat([1, 2, 3], [4, 5])) ===
|
||||
JSON.stringify([1, 2, 3, 4, 5])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function nonMutatingConcat(original, attach) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
var first = [1, 2, 3];
|
||||
var second = [4, 5];
|
||||
nonMutatingConcat(first, second);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function nonMutatingConcat(original, attach) {
|
||||
// Only change code below this line
|
||||
return original.concat(attach);
|
||||
// Only change code above this line
|
||||
}
|
||||
var first = [1, 2, 3];
|
||||
var second = [4, 5];
|
||||
nonMutatingConcat(first, second);
|
||||
```
|
@ -0,0 +1,75 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b62
|
||||
title: Implement map on a Prototype
|
||||
challengeType: 1
|
||||
forumTopicId: 301230
|
||||
dashedName: implement-map-on-a-prototype
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
As you have seen from applying `Array.prototype.map()`, or simply `map()` earlier, the `map` method returns an array of the same length as the one it was called on. It also doesn't alter the original array, as long as its callback function doesn't.
|
||||
|
||||
In other words, `map` is a pure function, and its output depends solely on its inputs. Plus, it takes another function as its argument.
|
||||
|
||||
You might learn a lot about the `map` method if you implement your own version of it. It is recommended you use a `for` loop or `Array.prototype.forEach()`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write your own `Array.prototype.myMap()`, which should behave exactly like `Array.prototype.map()`. You should not use the built-in `map` method. The `Array` instance can be accessed in the `myMap` method using `this`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`new_s` should equal `[46, 130, 196, 10]`.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(new_s) === JSON.stringify([46, 130, 196, 10]));
|
||||
```
|
||||
|
||||
Your code should not use the `map` method.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?map/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var s = [23, 65, 98, 5];
|
||||
|
||||
Array.prototype.myMap = function(callback) {
|
||||
var newArray = [];
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
return newArray;
|
||||
};
|
||||
|
||||
var new_s = s.myMap(function(item) {
|
||||
return item * 2;
|
||||
});
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// the global Array
|
||||
var s = [23, 65, 98, 5];
|
||||
|
||||
Array.prototype.myMap = function(callback) {
|
||||
var newArray = [];
|
||||
// Only change code below this line
|
||||
for (var elem of this) {
|
||||
newArray.push(callback(elem));
|
||||
}
|
||||
// Only change code above this line
|
||||
return newArray;
|
||||
};
|
||||
|
||||
var new_s = s.myMap(function(item) {
|
||||
return item * 2;
|
||||
});
|
||||
```
|
@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b64
|
||||
title: Implement the filter Method on a Prototype
|
||||
challengeType: 1
|
||||
forumTopicId: 301231
|
||||
dashedName: implement-the-filter-method-on-a-prototype
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You might learn a lot about the `filter` method if you implement your own version of it. It is recommended you use a `for` loop or `Array.prototype.forEach()`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write your own `Array.prototype.myFilter()`, which should behave exactly like `Array.prototype.filter()`. You should not use the built-in `filter` method. The `Array` instance can be accessed in the `myFilter` method using `this`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`new_s` should equal `[23, 65, 5]`.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(new_s) === JSON.stringify([23, 65, 5]));
|
||||
```
|
||||
|
||||
Your code should not use the `filter` method.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?filter/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var s = [23, 65, 98, 5];
|
||||
|
||||
Array.prototype.myFilter = function(callback) {
|
||||
// Only change code below this line
|
||||
var newArray = [];
|
||||
// Only change code above this line
|
||||
return newArray;
|
||||
};
|
||||
|
||||
var new_s = s.myFilter(function(item) {
|
||||
return item % 2 === 1;
|
||||
});
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// the global Array
|
||||
var s = [23, 65, 98, 5];
|
||||
|
||||
Array.prototype.myFilter = function(callback) {
|
||||
var newArray = [];
|
||||
// Only change code below this line
|
||||
for (let i = 0; i < this.length; i++) {
|
||||
if (callback(this[i])) newArray.push(this[i]);
|
||||
}
|
||||
// Only change code above this line
|
||||
return newArray;
|
||||
};
|
||||
|
||||
var new_s = s.myFilter(function(item) {
|
||||
return item % 2 === 1;
|
||||
});
|
||||
```
|
@ -0,0 +1,102 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b70
|
||||
title: Introduction to Currying and Partial Application
|
||||
challengeType: 1
|
||||
forumTopicId: 301232
|
||||
dashedName: introduction-to-currying-and-partial-application
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The <dfn>arity</dfn> of a function is the number of arguments it requires. <dfn>Currying</dfn> a function means to convert a function of N arity into N functions of arity 1.
|
||||
|
||||
In other words, it restructures a function so it takes one argument, then returns another function that takes the next argument, and so on.
|
||||
|
||||
Here's an example:
|
||||
|
||||
```js
|
||||
//Un-curried function
|
||||
function unCurried(x, y) {
|
||||
return x + y;
|
||||
}
|
||||
|
||||
//Curried function
|
||||
function curried(x) {
|
||||
return function(y) {
|
||||
return x + y;
|
||||
}
|
||||
}
|
||||
//Alternative using ES6
|
||||
const curried = x => y => x + y
|
||||
|
||||
curried(1)(2) // Returns 3
|
||||
```
|
||||
|
||||
This is useful in your program if you can't supply all the arguments to a function at one time. You can save each function call into a variable, which will hold the returned function reference that takes the next argument when it's available. Here's an example using the curried function in the example above:
|
||||
|
||||
```js
|
||||
// Call a curried function in parts:
|
||||
var funcForY = curried(1);
|
||||
console.log(funcForY(2)); // Prints 3
|
||||
```
|
||||
|
||||
Similarly, <dfn>partial application</dfn> can be described as applying a few arguments to a function at a time and returning another function that is applied to more arguments. Here's an example:
|
||||
|
||||
```js
|
||||
//Impartial function
|
||||
function impartial(x, y, z) {
|
||||
return x + y + z;
|
||||
}
|
||||
var partialFn = impartial.bind(this, 1, 2);
|
||||
partialFn(10); // Returns 13
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fill in the body of the `add` function so it uses currying to add parameters `x`, `y`, and `z`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`add(10)(20)(30)` should return `60`.
|
||||
|
||||
```js
|
||||
assert(add(10)(20)(30) === 60);
|
||||
```
|
||||
|
||||
`add(1)(2)(3)` should return `6`.
|
||||
|
||||
```js
|
||||
assert(add(1)(2)(3) === 6);
|
||||
```
|
||||
|
||||
`add(11)(22)(33)` should return `66`.
|
||||
|
||||
```js
|
||||
assert(add(11)(22)(33) === 66);
|
||||
```
|
||||
|
||||
Your code should include a final statement that returns `x + y + z`.
|
||||
|
||||
```js
|
||||
assert(code.match(/[xyz]\s*?\+\s*?[xyz]\s*?\+\s*?[xyz]/g));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function add(x) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
add(10)(20)(30);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const add = x => y => z => x + y + z
|
||||
```
|
@ -0,0 +1,88 @@
|
||||
---
|
||||
id: 587d7b8d367417b2b2512b5b
|
||||
title: Learn About Functional Programming
|
||||
challengeType: 1
|
||||
forumTopicId: 301233
|
||||
dashedName: learn-about-functional-programming
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Functional programming is a style of programming where solutions are simple, isolated functions, without any side effects outside of the function scope.
|
||||
|
||||
`INPUT -> PROCESS -> OUTPUT`
|
||||
|
||||
Functional programming is about:
|
||||
|
||||
1) Isolated functions - there is no dependence on the state of the program, which includes global variables that are subject to change
|
||||
|
||||
2) Pure functions - the same input always gives the same output
|
||||
|
||||
3) Functions with limited side effects - any changes, or mutations, to the state of the program outside the function are carefully controlled
|
||||
|
||||
# --instructions--
|
||||
|
||||
The members of freeCodeCamp happen to love tea.
|
||||
|
||||
In the code editor, the `prepareTea` and `getTea` functions are already defined for you. Call the `getTea` function to get 40 cups of tea for the team, and store them in the `tea4TeamFCC` variable.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `tea4TeamFCC` variable should hold 40 cups of tea for the team.
|
||||
|
||||
```js
|
||||
assert(tea4TeamFCC.length === 40);
|
||||
```
|
||||
|
||||
The `tea4TeamFCC` variable should hold cups of green tea.
|
||||
|
||||
```js
|
||||
assert(tea4TeamFCC[0] === 'greenTea');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Function that returns a string representing a cup of green tea
|
||||
const prepareTea = () => 'greenTea';
|
||||
|
||||
/*
|
||||
Given a function (representing the tea type) and number of cups needed, the
|
||||
following function returns an array of strings (each representing a cup of
|
||||
a specific type of tea).
|
||||
*/
|
||||
const getTea = (numOfCups) => {
|
||||
const teaCups = [];
|
||||
|
||||
for(let cups = 1; cups <= numOfCups; cups += 1) {
|
||||
const teaCup = prepareTea();
|
||||
teaCups.push(teaCup);
|
||||
}
|
||||
return teaCups;
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
const tea4TeamFCC = null;
|
||||
// Only change code above this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const prepareTea = () => 'greenTea';
|
||||
|
||||
const getTea = (numOfCups) => {
|
||||
const teaCups = [];
|
||||
|
||||
for(let cups = 1; cups <= numOfCups; cups += 1) {
|
||||
const teaCup = prepareTea();
|
||||
teaCups.push(teaCup);
|
||||
}
|
||||
|
||||
return teaCups;
|
||||
};
|
||||
|
||||
const tea4TeamFCC = getTea(40);
|
||||
```
|
@ -0,0 +1,80 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5f
|
||||
title: Pass Arguments to Avoid External Dependence in a Function
|
||||
challengeType: 1
|
||||
forumTopicId: 301234
|
||||
dashedName: pass-arguments-to-avoid-external-dependence-in-a-function
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The last challenge was a step closer to functional programming principles, but there is still something missing.
|
||||
|
||||
We didn't alter the global variable value, but the function `incrementer` would not work without the global variable `fixedValue` being there.
|
||||
|
||||
Another principle of functional programming is to always declare your dependencies explicitly. This means if a function depends on a variable or object being present, then pass that variable or object directly into the function as an argument.
|
||||
|
||||
There are several good consequences from this principle. The function is easier to test, you know exactly what input it takes, and it won't depend on anything else in your program.
|
||||
|
||||
This can give you more confidence when you alter, remove, or add new code. You would know what you can or cannot change and you can see where the potential traps are.
|
||||
|
||||
Finally, the function would always produce the same output for the same set of inputs, no matter what part of the code executes it.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Let's update the `incrementer` function to clearly declare its dependencies.
|
||||
|
||||
Write the `incrementer` function so it takes an argument, and then returns a result after increasing the value by one.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your function `incrementer` should not change the value of `fixedValue` (which is `4`).
|
||||
|
||||
```js
|
||||
assert(fixedValue === 4);
|
||||
```
|
||||
|
||||
Your `incrementer` function should take an argument.
|
||||
|
||||
```js
|
||||
assert(incrementer.length === 1);
|
||||
```
|
||||
|
||||
Your `incrementer` function should return a value that is one larger than the `fixedValue` value.
|
||||
|
||||
```js
|
||||
const __newValue = incrementer(fixedValue);
|
||||
assert(__newValue === 5);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var fixedValue = 4;
|
||||
|
||||
// Only change code below this line
|
||||
function incrementer () {
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var fixedValue = 4;
|
||||
|
||||
// Only change code below this line
|
||||
function incrementer (fixedValue) {
|
||||
return fixedValue + 1;
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
|
||||
```
|
@ -0,0 +1,141 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b60
|
||||
title: Refactor Global Variables Out of Functions
|
||||
challengeType: 1
|
||||
forumTopicId: 301235
|
||||
dashedName: refactor-global-variables-out-of-functions
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
So far, we have seen two distinct principles for functional programming:
|
||||
|
||||
1) Don't alter a variable or object - create new variables and objects and return them if need be from a function. Hint: using something like `var newArr = arrVar`, where `arrVar` is an array will simply create a reference to the existing variable and not a copy. So changing a value in `newArr` would change the value in `arrVar`.
|
||||
|
||||
2) Declare function parameters - any computation inside a function depends only on the arguments passed to the function, and not on any global object or variable.
|
||||
|
||||
Adding one to a number is not very exciting, but we can apply these principles when working with arrays or more complex objects.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Rewrite the code so the global array `bookList` is not changed inside either function. The `add` function should add the given `bookName` to the end of the array passed to it and return a new array (list). The `remove` function should remove the given `bookName` from the array passed to it.
|
||||
|
||||
**Note:** Both functions should return an array, and any new parameters should be added before the `bookName` parameter.
|
||||
|
||||
# --hints--
|
||||
|
||||
`bookList` should not change and still equal `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(bookList) ===
|
||||
JSON.stringify([
|
||||
'The Hound of the Baskervilles',
|
||||
'On The Electrodynamics of Moving Bodies',
|
||||
'Philosophiæ Naturalis Principia Mathematica',
|
||||
'Disquisitiones Arithmeticae'
|
||||
])
|
||||
);
|
||||
```
|
||||
|
||||
`newBookList` should equal `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(newBookList) ===
|
||||
JSON.stringify([
|
||||
'The Hound of the Baskervilles',
|
||||
'On The Electrodynamics of Moving Bodies',
|
||||
'Philosophiæ Naturalis Principia Mathematica',
|
||||
'Disquisitiones Arithmeticae',
|
||||
'A Brief History of Time'
|
||||
])
|
||||
);
|
||||
```
|
||||
|
||||
`newerBookList` should equal `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(newerBookList) ===
|
||||
JSON.stringify([
|
||||
'The Hound of the Baskervilles',
|
||||
'Philosophiæ Naturalis Principia Mathematica',
|
||||
'Disquisitiones Arithmeticae'
|
||||
])
|
||||
);
|
||||
```
|
||||
|
||||
`newestBookList` should equal `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(newestBookList) ===
|
||||
JSON.stringify([
|
||||
'The Hound of the Baskervilles',
|
||||
'Philosophiæ Naturalis Principia Mathematica',
|
||||
'Disquisitiones Arithmeticae',
|
||||
'A Brief History of Time'
|
||||
])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
|
||||
// Change code below this line
|
||||
function add (bookName) {
|
||||
|
||||
bookList.push(bookName);
|
||||
return bookList;
|
||||
|
||||
// Change code above this line
|
||||
}
|
||||
|
||||
// Change code below this line
|
||||
function remove (bookName) {
|
||||
var book_index = bookList.indexOf(bookName);
|
||||
if (book_index >= 0) {
|
||||
|
||||
bookList.splice(book_index, 1);
|
||||
return bookList;
|
||||
|
||||
// Change code above this line
|
||||
}
|
||||
}
|
||||
|
||||
var newBookList = add(bookList, 'A Brief History of Time');
|
||||
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
|
||||
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
|
||||
|
||||
console.log(bookList);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
|
||||
function add (bookList, bookName) {
|
||||
return [...bookList, bookName];
|
||||
}
|
||||
|
||||
function remove (bookList, bookName) {
|
||||
const bookListCopy = [...bookList];
|
||||
const bookNameIndex = bookList.indexOf(bookName);
|
||||
if (bookNameIndex >= 0) {
|
||||
bookListCopy.splice(bookNameIndex, 1);
|
||||
}
|
||||
return bookListCopy;
|
||||
}
|
||||
|
||||
var newBookList = add(bookList, 'A Brief History of Time');
|
||||
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
|
||||
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
|
||||
```
|
@ -0,0 +1,85 @@
|
||||
---
|
||||
id: 9d7123c8c441eeafaeb5bdef
|
||||
title: Remove Elements from an Array Using slice Instead of splice
|
||||
challengeType: 1
|
||||
forumTopicId: 301236
|
||||
dashedName: remove-elements-from-an-array-using-slice-instead-of-splice
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A common pattern while working with arrays is when you want to remove items and keep the rest of the array. JavaScript offers the `splice` method for this, which takes arguments for the index of where to start removing items, then the number of items to remove. If the second argument is not provided, the default is to remove items through the end. However, the `splice` method mutates the original array it is called on. Here's an example:
|
||||
|
||||
```js
|
||||
var cities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
|
||||
cities.splice(3, 1); // Returns "London" and deletes it from the cities array
|
||||
// cities is now ["Chicago", "Delhi", "Islamabad", "Berlin"]
|
||||
```
|
||||
|
||||
As we saw in the last challenge, the `slice` method does not mutate the original array, but returns a new one which can be saved into a variable. Recall that the `slice` method takes two arguments for the indices to begin and end the slice (the end is non-inclusive), and returns those items in a new array. Using the `slice` method instead of `splice` helps to avoid any array-mutating side effects.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Rewrite the function `nonMutatingSplice` by using `slice` instead of `splice`. It should limit the provided `cities` array to a length of 3, and return a new array with only the first three items.
|
||||
|
||||
Do not mutate the original array provided to the function.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `slice` method.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.slice/g));
|
||||
```
|
||||
|
||||
Your code should not use the `splice` method.
|
||||
|
||||
```js
|
||||
assert(!code.match(/\.?[\s\S]*?splice/g));
|
||||
```
|
||||
|
||||
The `inputCities` array should not change.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(inputCities) ===
|
||||
JSON.stringify(['Chicago', 'Delhi', 'Islamabad', 'London', 'Berlin'])
|
||||
);
|
||||
```
|
||||
|
||||
`nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])` should return `["Chicago", "Delhi", "Islamabad"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(
|
||||
nonMutatingSplice(['Chicago', 'Delhi', 'Islamabad', 'London', 'Berlin'])
|
||||
) === JSON.stringify(['Chicago', 'Delhi', 'Islamabad'])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function nonMutatingSplice(cities) {
|
||||
// Only change code below this line
|
||||
return cities.splice(3);
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
|
||||
nonMutatingSplice(inputCities);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function nonMutatingSplice(cities) {
|
||||
// Only change code below this line
|
||||
return cities.slice(0,3);
|
||||
// Only change code above this line
|
||||
}
|
||||
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
|
||||
nonMutatingSplice(inputCities);
|
||||
```
|
@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b6a
|
||||
title: Return a Sorted Array Without Changing the Original Array
|
||||
challengeType: 1
|
||||
forumTopicId: 301237
|
||||
dashedName: return-a-sorted-array-without-changing-the-original-array
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A side effect of the `sort` method is that it changes the order of the elements in the original array. In other words, it mutates the array in place. One way to avoid this is to first concatenate an empty array to the one being sorted (remember that `slice` and `concat` return a new array), then run the `sort` method.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `sort` method in the `nonMutatingSort` function to sort the elements of an array in ascending order. The function should return a new array, and not mutate the `globalArray` variable.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `sort` method.
|
||||
|
||||
```js
|
||||
assert(nonMutatingSort.toString().match(/\.sort/g));
|
||||
```
|
||||
|
||||
The `globalArray` variable should not change.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9]));
|
||||
```
|
||||
|
||||
`nonMutatingSort(globalArray)` should return `[2, 3, 5, 6, 9]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(nonMutatingSort(globalArray)) ===
|
||||
JSON.stringify([2, 3, 5, 6, 9])
|
||||
);
|
||||
```
|
||||
|
||||
`nonMutatingSort(globalArray)` should not be hard coded.
|
||||
|
||||
```js
|
||||
assert(!nonMutatingSort.toString().match(/[23569]/g));
|
||||
```
|
||||
|
||||
The function should return a new array, not the array passed to it.
|
||||
|
||||
```js
|
||||
assert(nonMutatingSort(globalArray) !== globalArray);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var globalArray = [5, 6, 3, 2, 9];
|
||||
function nonMutatingSort(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
nonMutatingSort(globalArray);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var globalArray = [5, 6, 3, 2, 9];
|
||||
function nonMutatingSort(arr) {
|
||||
// Only change code below this line
|
||||
return [].concat(arr).sort((a,b) => a-b);
|
||||
// Only change code above this line
|
||||
}
|
||||
nonMutatingSort(globalArray);
|
||||
```
|
@ -0,0 +1,94 @@
|
||||
---
|
||||
id: 587d7b90367417b2b2512b65
|
||||
title: Return Part of an Array Using the slice Method
|
||||
challengeType: 1
|
||||
forumTopicId: 301239
|
||||
dashedName: return-part-of-an-array-using-the-slice-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The `slice` method returns a copy of certain elements of an array. It can take two arguments, the first gives the index of where to begin the slice, the second is the index for where to end the slice (and it's non-inclusive). If the arguments are not provided, the default is to start at the beginning of the array through the end, which is an easy way to make a copy of the entire array. The `slice` method does not mutate the original array, but returns a new one.
|
||||
|
||||
Here's an example:
|
||||
|
||||
```js
|
||||
var arr = ["Cat", "Dog", "Tiger", "Zebra"];
|
||||
var newArray = arr.slice(1, 3);
|
||||
// Sets newArray to ["Dog", "Tiger"]
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `slice` method in the `sliceArray` function to return part of the `anim` array given the provided `beginSlice` and `endSlice` indices. The function should return an array.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `slice` method.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.slice/g));
|
||||
```
|
||||
|
||||
The `inputAnim` variable should not change.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(inputAnim) ===
|
||||
JSON.stringify(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'])
|
||||
);
|
||||
```
|
||||
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)` should return `["Dog", "Tiger"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 3)) ===
|
||||
JSON.stringify(['Dog', 'Tiger'])
|
||||
);
|
||||
```
|
||||
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)` should return `["Cat"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 0, 1)) ===
|
||||
JSON.stringify(['Cat'])
|
||||
);
|
||||
```
|
||||
|
||||
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)` should return `["Dog", "Tiger", "Zebra"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 4)) ===
|
||||
JSON.stringify(['Dog', 'Tiger', 'Zebra'])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function sliceArray(anim, beginSlice, endSlice) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
|
||||
sliceArray(inputAnim, 1, 3);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function sliceArray(anim, beginSlice, endSlice) {
|
||||
// Only change code below this line
|
||||
return anim.slice(beginSlice, endSlice)
|
||||
// Only change code above this line
|
||||
}
|
||||
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
|
||||
sliceArray(inputAnim, 1, 3);
|
||||
```
|
@ -0,0 +1,97 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b69
|
||||
title: Sort an Array Alphabetically using the sort Method
|
||||
challengeType: 1
|
||||
forumTopicId: 18303
|
||||
dashedName: sort-an-array-alphabetically-using-the-sort-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The `sort` method sorts the elements of an array according to the callback function.
|
||||
|
||||
For example:
|
||||
|
||||
```js
|
||||
function ascendingOrder(arr) {
|
||||
return arr.sort(function(a, b) {
|
||||
return a - b;
|
||||
});
|
||||
}
|
||||
ascendingOrder([1, 5, 2, 3, 4]);
|
||||
// Returns [1, 2, 3, 4, 5]
|
||||
|
||||
function reverseAlpha(arr) {
|
||||
return arr.sort(function(a, b) {
|
||||
return a === b ? 0 : a < b ? 1 : -1;
|
||||
});
|
||||
}
|
||||
reverseAlpha(['l', 'h', 'z', 'b', 's']);
|
||||
// Returns ['z', 's', 'l', 'h', 'b']
|
||||
```
|
||||
|
||||
JavaScript's default sorting method is by string Unicode point value, which may return unexpected results. Therefore, it is encouraged to provide a callback function to specify how to sort the array items. When such a callback function, normally called `compareFunction`, is supplied, the array elements are sorted according to the return value of the `compareFunction`: If `compareFunction(a,b)` returns a value less than 0 for two elements `a` and `b`, then `a` will come before `b`. If `compareFunction(a,b)` returns a value greater than 0 for two elements `a` and `b`, then `b` will come before `a`. If `compareFunction(a,b)` returns a value equal to 0 for two elements `a` and `b`, then `a` and `b` will remain unchanged.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `sort` method in the `alphabeticalOrder` function to sort the elements of `arr` in alphabetical order.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `sort` method.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.sort/g));
|
||||
```
|
||||
|
||||
`alphabeticalOrder(["a", "d", "c", "a", "z", "g"])` should return `["a", "a", "c", "d", "g", "z"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(alphabeticalOrder(['a', 'd', 'c', 'a', 'z', 'g'])) ===
|
||||
JSON.stringify(['a', 'a', 'c', 'd', 'g', 'z'])
|
||||
);
|
||||
```
|
||||
|
||||
`alphabeticalOrder(["x", "h", "a", "m", "n", "m"])` should return `["a", "h", "m", "m", "n", "x"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(alphabeticalOrder(['x', 'h', 'a', 'm', 'n', 'm'])) ===
|
||||
JSON.stringify(['a', 'h', 'm', 'm', 'n', 'x'])
|
||||
);
|
||||
```
|
||||
|
||||
`alphabeticalOrder(["a", "a", "a", "a", "x", "t"])` should return `["a", "a", "a", "a", "t", "x"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(alphabeticalOrder(['a', 'a', 'a', 'a', 'x', 't'])) ===
|
||||
JSON.stringify(['a', 'a', 'a', 'a', 't', 'x'])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function alphabeticalOrder(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function alphabeticalOrder(arr) {
|
||||
// Only change code below this line
|
||||
return arr.sort();
|
||||
// Only change code above this line
|
||||
}
|
||||
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
|
||||
```
|
@ -0,0 +1,88 @@
|
||||
---
|
||||
id: 587d7daa367417b2b2512b6b
|
||||
title: Split a String into an Array Using the split Method
|
||||
challengeType: 1
|
||||
forumTopicId: 18305
|
||||
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.
|
||||
|
||||
Here are two examples that split one string by spaces, then another by digits using a regular expression:
|
||||
|
||||
```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.
|
||||
|
||||
# --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.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `split` method.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.split/g));
|
||||
```
|
||||
|
||||
`splitify("Hello World,I-am code")` should return `["Hello", "World", "I", "am", "code"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(splitify('Hello World,I-am code')) ===
|
||||
JSON.stringify(['Hello', 'World', 'I', 'am', 'code'])
|
||||
);
|
||||
```
|
||||
|
||||
`splitify("Earth-is-our home")` should return `["Earth", "is", "our", "home"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(splitify('Earth-is-our home')) ===
|
||||
JSON.stringify(['Earth', 'is', 'our', 'home'])
|
||||
);
|
||||
```
|
||||
|
||||
`splitify("This.is.a-sentence")` should return `["This", "is", "a", "sentence"]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
JSON.stringify(splitify('This.is.a-sentence')) ===
|
||||
JSON.stringify(['This', 'is', 'a', 'sentence'])
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function splitify(str) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
splitify("Hello World,I-am code");
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function splitify(str) {
|
||||
// Only change code below this line
|
||||
return str.split(/\W/);
|
||||
// Only change code above this line
|
||||
}
|
||||
```
|
@ -0,0 +1,112 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5c
|
||||
title: Understand Functional Programming Terminology
|
||||
challengeType: 1
|
||||
forumTopicId: 301240
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
But first, let's cover some functional terminology:
|
||||
|
||||
<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.
|
||||
|
||||
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.
|
||||
|
||||
The functions that take a function as an argument, or return a function as a return value are called <dfn>higher order</dfn> functions.
|
||||
|
||||
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>.
|
||||
|
||||
# --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.
|
||||
|
||||
Note: The data (the number of cups of tea) is supplied as the last argument. We'll discuss this more in later lessons.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `tea4GreenTeamFCC` variable should hold 27 cups of green tea for the team.
|
||||
|
||||
```js
|
||||
assert(tea4GreenTeamFCC.length === 27);
|
||||
```
|
||||
|
||||
The `tea4GreenTeamFCC` variable should hold cups of green tea.
|
||||
|
||||
```js
|
||||
assert(tea4GreenTeamFCC[0] === 'greenTea');
|
||||
```
|
||||
|
||||
The `tea4BlackTeamFCC` variable should hold 13 cups of black tea.
|
||||
|
||||
```js
|
||||
assert(tea4BlackTeamFCC.length === 13);
|
||||
```
|
||||
|
||||
The `tea4BlackTeamFCC` variable should hold cups of black tea.
|
||||
|
||||
```js
|
||||
assert(tea4BlackTeamFCC[0] === 'blackTea');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Function that returns a string representing a cup of green tea
|
||||
const prepareGreenTea = () => 'greenTea';
|
||||
|
||||
// Function that returns a string representing a cup of black tea
|
||||
const prepareBlackTea = () => 'blackTea';
|
||||
|
||||
/*
|
||||
Given a function (representing the tea type) and number of cups needed, the
|
||||
following function returns an array of strings (each representing a cup of
|
||||
a specific type of tea).
|
||||
*/
|
||||
const getTea = (prepareTea, numOfCups) => {
|
||||
const teaCups = [];
|
||||
|
||||
for(let cups = 1; cups <= numOfCups; cups += 1) {
|
||||
const teaCup = prepareTea();
|
||||
teaCups.push(teaCup);
|
||||
}
|
||||
return teaCups;
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
const tea4GreenTeamFCC = null;
|
||||
const tea4BlackTeamFCC = null;
|
||||
// Only change code above this line
|
||||
|
||||
console.log(
|
||||
tea4GreenTeamFCC,
|
||||
tea4BlackTeamFCC
|
||||
);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const prepareGreenTea = () => 'greenTea';
|
||||
const prepareBlackTea = () => 'blackTea';
|
||||
|
||||
const getTea = (prepareTea, numOfCups) => {
|
||||
const teaCups = [];
|
||||
|
||||
for(let cups = 1; cups <= numOfCups; cups += 1) {
|
||||
const teaCup = prepareTea();
|
||||
teaCups.push(teaCup);
|
||||
}
|
||||
return teaCups;
|
||||
};
|
||||
|
||||
const tea4BlackTeamFCC = getTea(prepareBlackTea, 13);
|
||||
const tea4GreenTeamFCC = getTea(prepareGreenTea, 27);
|
||||
```
|
@ -0,0 +1,145 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5d
|
||||
title: Understand the Hazards of Using Imperative Code
|
||||
challengeType: 1
|
||||
forumTopicId: 301241
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
In contrast, functional programming is a form of declarative programming. You tell the computer what you want done by calling a method or function.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
# --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.
|
||||
|
||||
Change `Window.prototype.tabClose` so that it removes the correct tab.
|
||||
|
||||
# --hints--
|
||||
|
||||
`finalTabs.tabs` should be `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`
|
||||
|
||||
```js
|
||||
assert.deepEqual(finalTabs.tabs, [
|
||||
'FB',
|
||||
'Gitter',
|
||||
'Reddit',
|
||||
'Twitter',
|
||||
'Medium',
|
||||
'new tab',
|
||||
'Netflix',
|
||||
'YouTube',
|
||||
'Vine',
|
||||
'GMail',
|
||||
'Work mail',
|
||||
'Docs',
|
||||
'freeCodeCamp',
|
||||
'new tab'
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// tabs is an array of titles of each site open within the window
|
||||
var Window = function(tabs) {
|
||||
this.tabs = tabs; // We keep a record of the array inside the object
|
||||
};
|
||||
|
||||
// When you join two windows into one window
|
||||
Window.prototype.join = function (otherWindow) {
|
||||
this.tabs = this.tabs.concat(otherWindow.tabs);
|
||||
return this;
|
||||
};
|
||||
|
||||
// When you open a new tab at the end
|
||||
Window.prototype.tabOpen = function (tab) {
|
||||
this.tabs.push('new tab'); // Let's open a new tab for now
|
||||
return this;
|
||||
};
|
||||
|
||||
// When you close a tab
|
||||
Window.prototype.tabClose = function (index) {
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var tabsBeforeIndex = this.tabs.splice(0, index); // Get the tabs before the tab
|
||||
var tabsAfterIndex = this.tabs.splice(index + 1); // Get the tabs after the tab
|
||||
|
||||
this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // Join them together
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
// Let's create three browser windows
|
||||
var workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']); // Your mailbox, drive, and other work sites
|
||||
var socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']); // Social sites
|
||||
var videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']); // Entertainment sites
|
||||
|
||||
// Now perform the tab opening, closing, and other operations
|
||||
var finalTabs = socialWindow
|
||||
.tabOpen() // Open a new tab for cat memes
|
||||
.join(videoWindow.tabClose(2)) // Close third tab in video window, and join
|
||||
.join(workWindow.tabClose(1).tabOpen());
|
||||
console.log(finalTabs.tabs);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// tabs is an array of titles of each site open within the window
|
||||
var Window = function(tabs) {
|
||||
this.tabs = tabs; // We keep a record of the array inside the object
|
||||
};
|
||||
|
||||
// When you join two windows into one window
|
||||
Window.prototype.join = function (otherWindow) {
|
||||
this.tabs = this.tabs.concat(otherWindow.tabs);
|
||||
return this;
|
||||
};
|
||||
|
||||
// When you open a new tab at the end
|
||||
Window.prototype.tabOpen = function (tab) {
|
||||
this.tabs.push('new tab'); // Let's open a new tab for now
|
||||
return this;
|
||||
};
|
||||
|
||||
// When you close a tab
|
||||
Window.prototype.tabClose = function (index) {
|
||||
var tabsBeforeIndex = this.tabs.slice(0, index); // Get the tabs before the tab
|
||||
var tabsAfterIndex = this.tabs.slice(index + 1); // Get the tabs after the tab
|
||||
|
||||
this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // Join them together
|
||||
return this;
|
||||
};
|
||||
|
||||
// Let's create three browser windows
|
||||
var workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']); // Your mailbox, drive, and other work sites
|
||||
var socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']); // Social sites
|
||||
var videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']); // Entertainment sites
|
||||
|
||||
// Now perform the tab opening, closing, and other operations
|
||||
var finalTabs = socialWindow
|
||||
.tabOpen() // Open a new tab for cat memes
|
||||
.join(videoWindow.tabClose(2)) // Close third tab in video window, and join
|
||||
.join(workWindow.tabClose(1).tabOpen());
|
||||
```
|
@ -0,0 +1,97 @@
|
||||
---
|
||||
id: 587d7b88367417b2b2512b45
|
||||
title: 'Use Higher-Order Functions map, filter, or reduce to Solve a Complex Problem'
|
||||
challengeType: 1
|
||||
forumTopicId: 301311
|
||||
dashedName: use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-problem
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Now that you have worked through a few challenges using higher-order functions like `map()`, `filter()`, and `reduce()`, you now get to apply them to solve a more complex challenge.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function named `squareList`. You need to complete the code for the `squareList` function using any combination of `map()`, `filter()`, and `reduce()` so that it returns a new array containing only the square of *only* the positive integers (decimal numbers are not integers) when an array of real numbers is passed to it. An example of an array containing only real numbers is `[-3, 4.8, 5, 3, -3.2]`.
|
||||
|
||||
**Note:** Your function should not use any kind of `for` or `while` loops or the `forEach()` function.
|
||||
|
||||
# --hints--
|
||||
|
||||
`squareList` should be a `function`.
|
||||
|
||||
```js
|
||||
assert.typeOf(squareList, 'function'),
|
||||
'<code>squareList</code> should be a <code>function</code>';
|
||||
```
|
||||
|
||||
`for`, `while`, and `forEach` should not be used.
|
||||
|
||||
```js
|
||||
assert(!__helpers.removeJSComments(code).match(/for|while|forEach/g));
|
||||
```
|
||||
|
||||
`map`, `filter`, or `reduce` should be used.
|
||||
|
||||
```js
|
||||
assert(
|
||||
__helpers
|
||||
.removeWhiteSpace(__helpers.removeJSComments(code))
|
||||
.match(/\.(map|filter|reduce)\(/g)
|
||||
);
|
||||
```
|
||||
|
||||
The function should return an `array`.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])));
|
||||
```
|
||||
|
||||
`squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])` should return `[16, 1764, 36]`.
|
||||
|
||||
```js
|
||||
assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [
|
||||
16,
|
||||
1764,
|
||||
36
|
||||
]);
|
||||
```
|
||||
|
||||
`squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])` should return `[9, 100, 49]`.
|
||||
|
||||
```js
|
||||
assert.deepStrictEqual(squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]), [
|
||||
9,
|
||||
100,
|
||||
49
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
const squareList = arr => {
|
||||
// Only change code below this line
|
||||
return arr;
|
||||
// Only change code above this line
|
||||
};
|
||||
|
||||
const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
|
||||
console.log(squaredIntegers);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
const squareList = arr => {
|
||||
const positiveIntegers = arr.filter(num => {
|
||||
return num >= 0 && Number.isInteger(num);
|
||||
});
|
||||
const squaredIntegers = positiveIntegers.map(num => {
|
||||
return num ** 2;
|
||||
});
|
||||
return squaredIntegers;
|
||||
};
|
||||
```
|
@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6e
|
||||
title: Use the every Method to Check that Every Element in an Array Meets a Criteria
|
||||
challengeType: 1
|
||||
forumTopicId: 301312
|
||||
dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria
|
||||
---
|
||||
|
||||
# --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.
|
||||
|
||||
For example, the following code would check if every element in the `numbers` array is less than 10:
|
||||
|
||||
```js
|
||||
var numbers = [1, 5, 8, 0, 10, 11];
|
||||
numbers.every(function(currentValue) {
|
||||
return currentValue < 10;
|
||||
});
|
||||
// Returns false
|
||||
```
|
||||
|
||||
# --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.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `every` method.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.every/g));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, -4, 5])` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(checkPositive([1, 2, 3, -4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, 4, 5])` should return `true`.
|
||||
|
||||
```js
|
||||
assert.isTrue(checkPositive([1, 2, 3, 4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([1, -2, 3, -4, 5])` should return `false`.
|
||||
|
||||
```js
|
||||
assert.isFalse(checkPositive([1, -2, 3, -4, 5]));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function checkPositive(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
checkPositive([1, 2, 3, -4, 5]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function checkPositive(arr) {
|
||||
// Only change code below this line
|
||||
return arr.every(num => num > 0);
|
||||
// Only change code above this line
|
||||
}
|
||||
checkPositive([1, 2, 3, -4, 5]);
|
||||
```
|
@ -0,0 +1,315 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b63
|
||||
title: Use the filter Method to Extract Data from an Array
|
||||
challengeType: 1
|
||||
forumTopicId: 18179
|
||||
dashedName: use-the-filter-method-to-extract-data-from-an-array
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Another useful array function is `Array.prototype.filter()`, or simply `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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
```js
|
||||
const users = [
|
||||
{ name: 'John', age: 34 },
|
||||
{ name: 'Amy', age: 20 },
|
||||
{ name: 'camperCat', age: 10 }
|
||||
];
|
||||
|
||||
const usersUnder30 = users.filter(user => user.age < 30);
|
||||
console.log(usersUnder30); // [ { 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.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `watchList` variable should not change.
|
||||
|
||||
```js
|
||||
assert(
|
||||
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
|
||||
);
|
||||
```
|
||||
|
||||
Your code should use the `filter` method.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.filter/g));
|
||||
```
|
||||
|
||||
Your code should not use a `for` loop.
|
||||
|
||||
```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"}]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(filteredList, [
|
||||
{ title: 'Inception', rating: '8.8' },
|
||||
{ title: 'Interstellar', rating: '8.6' },
|
||||
{ title: 'The Dark Knight', rating: '9.0' },
|
||||
{ title: 'Batman Begins', rating: '8.3' }
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// 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"
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var filteredList;
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
console.log(filteredList);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// 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"
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
let filteredList = watchList.filter(e => e.imdbRating >= 8).map( ({Title: title, imdbRating: rating}) => ({title, rating}) );
|
||||
// Only change code above this line
|
||||
```
|
@ -0,0 +1,328 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b61
|
||||
title: Use the map Method to Extract Data from an Array
|
||||
challengeType: 1
|
||||
forumTopicId: 18214
|
||||
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.
|
||||
|
||||
This is only the beginning. As its name suggests, functional programming is centered around a theory of functions.
|
||||
|
||||
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.
|
||||
|
||||
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`.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
```js
|
||||
const users = [
|
||||
{ name: 'John', age: 34 },
|
||||
{ name: 'Amy', age: 20 },
|
||||
{ name: 'camperCat', age: 10 }
|
||||
];
|
||||
|
||||
const names = users.map(user => user.name);
|
||||
console.log(names); // [ '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.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `watchList` variable should not change.
|
||||
|
||||
```js
|
||||
assert(
|
||||
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
|
||||
);
|
||||
```
|
||||
|
||||
Your code should not use a `for` loop.
|
||||
|
||||
```js
|
||||
assert(!__helpers.removeJSComments(code).match(/for\s*?\([\s\S]*?\)/));
|
||||
```
|
||||
|
||||
Your code should use the `map` method.
|
||||
|
||||
```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"}]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(ratings, [
|
||||
{ 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' }
|
||||
]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// 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"
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var ratings = [];
|
||||
for(var i=0; i < watchList.length; i++){
|
||||
ratings.push({title: watchList[i]["Title"], rating: watchList[i]["imdbRating"]});
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
console.log(JSON.stringify(ratings));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// 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"
|
||||
}
|
||||
];
|
||||
|
||||
var ratings = watchList.map(function(movie) {
|
||||
return {
|
||||
title: movie["Title"],
|
||||
rating: movie["imdbRating"]
|
||||
}
|
||||
});
|
||||
```
|
@ -0,0 +1,341 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b68
|
||||
title: Use the reduce Method to Analyze Data
|
||||
challengeType: 1
|
||||
forumTopicId: 301313
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
```js
|
||||
const users = [
|
||||
{ name: 'John', age: 34 },
|
||||
{ name: 'Amy', age: 20 },
|
||||
{ name: 'camperCat', age: 10 }
|
||||
];
|
||||
|
||||
const sumOfAges = users.reduce((sum, user) => sum + user.age, 0);
|
||||
console.log(sumOfAges); // 64
|
||||
```
|
||||
|
||||
In another example, see how an object can be returned containing the names of the users as properties with their ages as values.
|
||||
|
||||
```js
|
||||
const users = [
|
||||
{ name: 'John', age: 34 },
|
||||
{ name: 'Amy', age: 20 },
|
||||
{ name: 'camperCat', age: 10 }
|
||||
];
|
||||
|
||||
const usersObj = users.reduce((obj, user) => {
|
||||
obj[user.name] = user.age;
|
||||
return obj;
|
||||
}, {});
|
||||
console.log(usersObj); // { 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.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `watchList` variable should not change.
|
||||
|
||||
```js
|
||||
assert(
|
||||
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
|
||||
);
|
||||
```
|
||||
|
||||
Your code should use the `reduce` method.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.reduce/g));
|
||||
```
|
||||
|
||||
The `getRating(watchList)` should equal 8.675.
|
||||
|
||||
```js
|
||||
assert(getRating(watchList) === 8.675);
|
||||
```
|
||||
|
||||
Your code should not use a `for` loop.
|
||||
|
||||
```js
|
||||
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
|
||||
```
|
||||
|
||||
Your code should return correct output after modifying the `watchList` object.
|
||||
|
||||
```js
|
||||
assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// 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"
|
||||
}
|
||||
];
|
||||
|
||||
function getRating(watchList){
|
||||
// Only change code below this line
|
||||
var averageRating;
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
return averageRating;
|
||||
}
|
||||
console.log(getRating(watchList));
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// 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"
|
||||
}
|
||||
];
|
||||
|
||||
function getRating(watchList){
|
||||
var averageRating;
|
||||
const rating = watchList
|
||||
.filter(obj => obj.Director === "Christopher Nolan")
|
||||
.map(obj => Number(obj.imdbRating));
|
||||
averageRating = rating.reduce((accum, curr) => accum + curr)/rating.length;
|
||||
return averageRating;
|
||||
}
|
||||
```
|
@ -0,0 +1,76 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6f
|
||||
title: Use the some Method to Check that Any Elements in an Array Meet a Criteria
|
||||
challengeType: 1
|
||||
forumTopicId: 301314
|
||||
dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria
|
||||
---
|
||||
|
||||
# --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.
|
||||
|
||||
For example, the following code would check if any element in the `numbers` array is less than 10:
|
||||
|
||||
```js
|
||||
var numbers = [10, 50, 8, 220, 110, 11];
|
||||
numbers.some(function(currentValue) {
|
||||
return currentValue < 10;
|
||||
});
|
||||
// Returns 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.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use the `some` method.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.some/g));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, -4, 5])` should return `true`.
|
||||
|
||||
```js
|
||||
assert(checkPositive([1, 2, 3, -4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([1, 2, 3, 4, 5])` should return `true`.
|
||||
|
||||
```js
|
||||
assert(checkPositive([1, 2, 3, 4, 5]));
|
||||
```
|
||||
|
||||
`checkPositive([-1, -2, -3, -4, -5])` should return `false`.
|
||||
|
||||
```js
|
||||
assert(!checkPositive([-1, -2, -3, -4, -5]));
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function checkPositive(arr) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
checkPositive([1, 2, 3, -4, 5]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function checkPositive(arr) {
|
||||
// Only change code below this line
|
||||
return arr.some(elem => elem > 0);
|
||||
// Only change code above this line
|
||||
}
|
||||
checkPositive([1, 2, 3, -4, 5]);
|
||||
```
|
Reference in New Issue
Block a user