Feat: add new Markdown parser (#39800)

and change all the challenges to new `md` format.
This commit is contained in:
Oliver Eyton-Williams
2020-11-27 19:02:05 +01:00
committed by GitHub
parent a07f84c8ec
commit 0bd52f8bd1
2580 changed files with 113436 additions and 111979 deletions

View File

@@ -5,61 +5,65 @@ challengeType: 1
forumTopicId: 301149
---
## Description
<section id='description'>
# --description--
The fundamental feature of any data structure is, of course, the ability to not only store data, but to be able to retrieve that data on command. So, now that we've learned how to create an array, let's begin to think about how we can access that array's information.
When we define a simple array as seen below, there are 3 items in it:
```js
let ourArray = ["a", "b", "c"];
```
In an array, each array item has an <dfn>index</dfn>. This index doubles as the position of that item in the array, and how you reference it. However, it is important to note, that JavaScript arrays are <dfn>zero-indexed</dfn>, meaning that the first element of an array is actually at the <em><strong>zeroth</strong></em> position, not the first.
In order to retrieve an element from an array we can enclose an index in brackets and append it to the end of an array, or more commonly, to a variable which references an array object. This is known as <dfn>bracket notation</dfn>.
For example, if we want to retrieve the <code>"a"</code> from <code>ourArray</code> and assign it to a variable, we can do so with the following code:
In an array, each array item has an <dfn>index</dfn>. This index doubles as the position of that item in the array, and how you reference it. However, it is important to note, that JavaScript arrays are <dfn>zero-indexed</dfn>, meaning that the first element of an array is actually at the ***zeroth*** position, not the first. In order to retrieve an element from an array we can enclose an index in brackets and append it to the end of an array, or more commonly, to a variable which references an array object. This is known as <dfn>bracket notation</dfn>. For example, if we want to retrieve the `"a"` from `ourArray` and assign it to a variable, we can do so with the following code:
```js
let ourVariable = ourArray[0];
// ourVariable equals "a"
```
In addition to accessing the value associated with an index, you can also <em>set</em> an index to a value using the same notation:
In addition to accessing the value associated with an index, you can also *set* an index to a value using the same notation:
```js
ourArray[1] = "not b anymore";
// ourArray now equals ["a", "not b anymore", "c"];
```
Using bracket notation, we have now reset the item at index 1 from <code>"b"</code>, to <code>"not b anymore"</code>.
</section>
Using bracket notation, we have now reset the item at index 1 from `"b"`, to `"not b anymore"`.
## Instructions
<section id='instructions'>
In order to complete this challenge, set the 2nd position (index <code>1</code>) of <code>myArray</code> to anything you want, besides <code>"b"</code>.
</section>
# --instructions--
## Tests
<section id='tests'>
In order to complete this challenge, set the 2nd position (index `1`) of `myArray` to anything you want, besides `"b"`.
```yml
tests:
- text: <code>myArray[0]</code> should be equal to <code>"a"</code>
testString: assert.strictEqual(myArray[0], "a");
- text: <code>myArray[1]</code> should not be equal to <code>"b"</code>
testString: assert.notStrictEqual(myArray[1], "b");
- text: <code>myArray[2]</code> should be equal to <code>"c"</code>
testString: assert.strictEqual(myArray[2], "c");
- text: <code>myArray[3]</code> should be equal to <code>"d"</code>
testString: assert.strictEqual(myArray[3], "d");
# --hints--
`myArray[0]` should be equal to `"a"`
```js
assert.strictEqual(myArray[0], 'a');
```
</section>
`myArray[1]` should not be equal to `"b"`
## Challenge Seed
<section id='challengeSeed'>
```js
assert.notStrictEqual(myArray[1], 'b');
```
<div id='js-seed'>
`myArray[2]` should be equal to `"c"`
```js
assert.strictEqual(myArray[2], 'c');
```
`myArray[3]` should be equal to `"d"`
```js
assert.strictEqual(myArray[3], 'd');
```
# --seed--
## --seed-contents--
```js
let myArray = ["a", "b", "c", "d"];
@@ -69,18 +73,9 @@ let myArray = ["a", "b", "c", "d"];
console.log(myArray);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
let myArray = ["a", "b", "c", "d"];
myArray[1] = "e";
```
</section>

View File

@@ -5,47 +5,63 @@ challengeType: 1
forumTopicId: 301150
---
## Description
<section id='description'>
In the first object challenge we mentioned the use of bracket notation as a way to access property values using the evaluation of a variable. For instance, imagine that our <code>foods</code> object is being used in a program for a supermarket cash register. We have some function that sets the <code>selectedFood</code> and we want to check our <code>foods</code> object for the presence of that food. This might look like:
# --description--
In the first object challenge we mentioned the use of bracket notation as a way to access property values using the evaluation of a variable. For instance, imagine that our `foods` object is being used in a program for a supermarket cash register. We have some function that sets the `selectedFood` and we want to check our `foods` object for the presence of that food. This might look like:
```js
let selectedFood = getCurrentFood(scannedItem);
let inventory = foods[selectedFood];
```
This code will evaluate the value stored in the <code>selectedFood</code> variable and return the value of that key in the <code>foods</code> object, or <code>undefined</code> if it is not present. Bracket notation is very useful because sometimes object properties are not known before runtime or we need to access them in a more dynamic way.
</section>
This code will evaluate the value stored in the `selectedFood` variable and return the value of that key in the `foods` object, or `undefined` if it is not present. Bracket notation is very useful because sometimes object properties are not known before runtime or we need to access them in a more dynamic way.
## Instructions
<section id='instructions'>
We've defined a function, <code>checkInventory</code>, which receives a scanned item as an argument. Return the current value of the <code>scannedItem</code> key in the <code>foods</code> object. You can assume that only valid keys will be provided as an argument to <code>checkInventory</code>.
</section>
# --instructions--
## Tests
<section id='tests'>
We've defined a function, `checkInventory`, which receives a scanned item as an argument. Return the current value of the `scannedItem` key in the `foods` object. You can assume that only valid keys will be provided as an argument to `checkInventory`.
```yml
tests:
- text: <code>checkInventory</code> should be a function.
testString: assert.strictEqual(typeof checkInventory, 'function');
- text: 'The <code>foods</code> object should have only the following key-value pairs: <code>apples: 25</code>, <code>oranges: 32</code>, <code>plums: 28</code>, <code>bananas: 13</code>, <code>grapes: 35</code>, <code>strawberries: 27</code>.'
testString: 'assert.deepEqual(foods, {apples: 25, oranges: 32, plums: 28, bananas: 13, grapes: 35, strawberries: 27});'
- text: <code>checkInventory("apples")</code> should return <code>25</code>.
testString: assert.strictEqual(checkInventory('apples'), 25);
- text: <code>checkInventory("bananas")</code> should return <code>13</code>.
testString: assert.strictEqual(checkInventory('bananas'), 13);
- text: <code>checkInventory("strawberries")</code> should return <code>27</code>.
testString: assert.strictEqual(checkInventory('strawberries'), 27);
# --hints--
`checkInventory` should be a function.
```js
assert.strictEqual(typeof checkInventory, 'function');
```
</section>
The `foods` object should have only the following key-value pairs: `apples: 25`, `oranges: 32`, `plums: 28`, `bananas: 13`, `grapes: 35`, `strawberries: 27`.
## Challenge Seed
<section id='challengeSeed'>
```js
assert.deepEqual(foods, {
apples: 25,
oranges: 32,
plums: 28,
bananas: 13,
grapes: 35,
strawberries: 27
});
```
<div id='js-seed'>
`checkInventory("apples")` should return `25`.
```js
assert.strictEqual(checkInventory('apples'), 25);
```
`checkInventory("bananas")` should return `13`.
```js
assert.strictEqual(checkInventory('bananas'), 13);
```
`checkInventory("strawberries")` should return `27`.
```js
assert.strictEqual(checkInventory('strawberries'), 27);
```
# --seed--
## --seed-contents--
```js
let foods = {
@@ -66,14 +82,7 @@ function checkInventory(scannedItem) {
console.log(checkInventory("apples"));
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
let foods = {
@@ -89,5 +98,3 @@ function checkInventory(scannedItem) {
return foods[scannedItem];
}
```
</section>

View File

@@ -5,10 +5,11 @@ challengeType: 1
forumTopicId: 301151
---
## Description
<section id='description'>
An array's length, like the data types it can contain, is not fixed. Arrays can be defined with a length of any number of elements, and elements can be added or removed over time; in other words, arrays are <dfn>mutable</dfn>. In this challenge, we will look at two methods with which we can programmatically modify an array: <code>Array.push()</code> and <code>Array.unshift()</code>.
Both methods take one or more elements as parameters and add those elements to the array the method is being called on; the <code>push()</code> method adds elements to the end of an array, and <code>unshift()</code> adds elements to the beginning. Consider the following:
# --description--
An array's length, like the data types it can contain, is not fixed. Arrays can be defined with a length of any number of elements, and elements can be added or removed over time; in other words, arrays are <dfn>mutable</dfn>. In this challenge, we will look at two methods with which we can programmatically modify an array: `Array.push()` and `Array.unshift()`.
Both methods take one or more elements as parameters and add those elements to the array the method is being called on; the `push()` method adds elements to the end of an array, and `unshift()` adds elements to the beginning. Consider the following:
```js
let twentyThree = 'XXIII';
@@ -21,33 +22,43 @@ romanNumerals.push(twentyThree);
// now equals ['XIX', 'XX', 'XXI', 'XXII', 'XXIII']Notice that we can also pass variables, which allows us even greater flexibility in dynamically modifying our array's data.
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
We have defined a function, <code>mixedNumbers</code>, which we are passing an array as an argument. Modify the function by using <code>push()</code> and <code>unshift()</code> to add <code>'I', 2, 'three'</code> to the beginning of the array and <code>7, 'VIII', 9</code> to the end so that the returned array contains representations of the numbers 1-9 in order.
</section>
We have defined a function, `mixedNumbers`, which we are passing an array as an argument. Modify the function by using `push()` and `unshift()` to add `'I', 2, 'three'` to the beginning of the array and `7, 'VIII', 9` to the end so that the returned array contains representations of the numbers 1-9 in order.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: <code>mixedNumbers(["IV", 5, "six"])</code> should now return <code>["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]</code>
testString: assert.deepEqual(mixedNumbers(['IV', 5, 'six']), ['I', 2, 'three', 'IV', 5, 'six', 7, 'VIII', 9]);
- text: The <code>mixedNumbers</code> function should utilize the <code>push()</code> method
testString: assert(mixedNumbers.toString().match(/\.push/));
- text: The <code>mixedNumbers</code> function should utilize the <code>unshift()</code> method
testString: assert(mixedNumbers.toString().match(/\.unshift/));
`mixedNumbers(["IV", 5, "six"])` should now return `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`
```js
assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
'I',
2,
'three',
'IV',
5,
'six',
7,
'VIII',
9
]);
```
</section>
The `mixedNumbers` function should utilize the `push()` method
## Challenge Seed
<section id='challengeSeed'>
```js
assert(mixedNumbers.toString().match(/\.push/));
```
<div id='js-seed'>
The `mixedNumbers` function should utilize the `unshift()` method
```js
assert(mixedNumbers.toString().match(/\.unshift/));
```
# --seed--
## --seed-contents--
```js
function mixedNumbers(arr) {
@@ -60,14 +71,7 @@ function mixedNumbers(arr) {
console.log(mixedNumbers(['IV', 5, 'six']));
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function mixedNumbers(arr) {
@@ -76,5 +80,3 @@ function mixedNumbers(arr) {
return arr;
}
```
</section>

View File

@@ -5,9 +5,9 @@ challengeType: 1
forumTopicId: 301152
---
## Description
<section id='description'>
Remember in the last challenge we mentioned that <code>splice()</code> can take up to three parameters? Well, you can use the third parameter, comprised of one or more element(s), to add to the array. This can be incredibly useful for quickly switching out an element, or a set of elements, for another.
# --description--
Remember in the last challenge we mentioned that `splice()` can take up to three parameters? Well, you can use the third parameter, comprised of one or more element(s), to add to the array. This can be incredibly useful for quickly switching out an element, or a set of elements, for another.
```js
const numbers = [10, 11, 12, 12, 15];
@@ -20,36 +20,56 @@ console.log(numbers);
// returns [ 10, 11, 12, 13, 14, 15 ]
```
Here we begin with an array of numbers. We then pass the following to <code>splice()</code>. The index at which to begin deleting elements (3), the number of elements to be deleted (1), and the elements (13, 14) to be inserted at that same index. Note that there can be any number of elements (separated by commas) following <code>amountToDelete</code>, each of which gets inserted.
</section>
Here we begin with an array of numbers. We then pass the following to `splice()`. The index at which to begin deleting elements (3), the number of elements to be deleted (1), and the elements (13, 14) to be inserted at that same index. Note that there can be any number of elements (separated by commas) following `amountToDelete`, each of which gets inserted.
## Instructions
<section id='instructions'>
We have defined a function, <code>htmlColorNames</code>, which takes an array of HTML colors as an argument. Modify the function using <code>splice()</code> to remove the first two elements of the array and add <code>'DarkSalmon'</code> and <code>'BlanchedAlmond'</code> in their respective places.
</section>
# --instructions--
## Tests
<section id='tests'>
We have defined a function, `htmlColorNames`, which takes an array of HTML colors as an argument. Modify the function using `splice()` to remove the first two elements of the array and add `'DarkSalmon'` and `'BlanchedAlmond'` in their respective places.
```yml
tests:
- text: <code>htmlColorNames</code> should return <code>["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]</code>
testString: assert.deepEqual(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurquoise', 'FireBrick']), ['DarkSalmon', 'BlanchedAlmond', 'LavenderBlush', 'PaleTurquoise', 'FireBrick']);
- text: The <code>htmlColorNames</code> function should utilize the <code>splice()</code> method
testString: assert(/.splice/.test(code));
- text: You should not use <code>shift()</code> or <code>unshift()</code>.
testString: assert(!/shift|unshift/.test(code));
- text: You should not use array bracket notation.
testString: assert(!/\[\d\]\s*=/.test(code));
# --hints--
`htmlColorNames` should return `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]`
```js
assert.deepEqual(
htmlColorNames([
'DarkGoldenRod',
'WhiteSmoke',
'LavenderBlush',
'PaleTurquoise',
'FireBrick'
]),
[
'DarkSalmon',
'BlanchedAlmond',
'LavenderBlush',
'PaleTurquoise',
'FireBrick'
]
);
```
</section>
The `htmlColorNames` function should utilize the `splice()` method
## Challenge Seed
<section id='challengeSeed'>
```js
assert(/.splice/.test(code));
```
<div id='js-seed'>
You should not use `shift()` or `unshift()`.
```js
assert(!/shift|unshift/.test(code));
```
You should not use array bracket notation.
```js
assert(!/\[\d\]\s*=/.test(code));
```
# --seed--
## --seed-contents--
```js
function htmlColorNames(arr) {
@@ -62,14 +82,7 @@ function htmlColorNames(arr) {
console.log(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurquoise', 'FireBrick']));
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function htmlColorNames(arr) {
@@ -77,5 +90,3 @@ function htmlColorNames(arr) {
return arr;
}
```
</section>

View File

@@ -5,8 +5,8 @@ challengeType: 1
forumTopicId: 301153
---
## Description
<section id='description'>
# --description--
At their most basic, objects are just collections of <dfn>key-value</dfn> pairs. In other words, they are pieces of data (<dfn>values</dfn>) mapped to unique identifiers called <dfn>properties</dfn> (<dfn>keys</dfn>). Take a look at an example:
```js
@@ -17,13 +17,13 @@ const tekkenCharacter = {
};
```
The above code defines a Tekken video game character object called <code>tekkenCharacter</code>. It has three properties, each of which map to a specific value. If you want to add an additional property, such as "origin", it can be done by assigning <code>origin</code> to the object:
The above code defines a Tekken video game character object called `tekkenCharacter`. It has three properties, each of which map to a specific value. If you want to add an additional property, such as "origin", it can be done by assigning `origin` to the object:
```js
tekkenCharacter.origin = 'South Korea';
```
This uses dot notation. If you were to observe the <code>tekkenCharacter</code> object, it will now include the <code>origin</code> property. Hwoarang also had distinct orange hair. You can add this property with bracket notation by doing:
This uses dot notation. If you were to observe the `tekkenCharacter` object, it will now include the `origin` property. Hwoarang also had distinct orange hair. You can add this property with bracket notation by doing:
```js
tekkenCharacter['hair color'] = 'dyed orange';
@@ -50,37 +50,49 @@ After adding all the examples, the object will look like this:
};
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
A <code>foods</code> object has been created with three entries. Using the syntax of your choice, add three more entries to it: <code>bananas</code> with a value of <code>13</code>, <code>grapes</code> with a value of <code>35</code>, and <code>strawberries</code> with a value of <code>27</code>.
</section>
A `foods` object has been created with three entries. Using the syntax of your choice, add three more entries to it: `bananas` with a value of `13`, `grapes` with a value of `35`, and `strawberries` with a value of `27`.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: <code>foods</code> should be an object.
testString: assert(typeof foods === 'object');
- text: The <code>foods</code> object should have a key <code>"bananas"</code> with a value of <code>13</code>.
testString: assert(foods.bananas === 13);
- text: The <code>foods</code> object should have a key <code>"grapes"</code> with a value of <code>35</code>.
testString: assert(foods.grapes === 35);
- text: The <code>foods</code> object should have a key <code>"strawberries"</code> with a value of <code>27</code>.
testString: assert(foods.strawberries === 27);
- text: The key-value pairs should be set using dot or bracket notation.
testString: assert(code.search(/bananas:/) === -1 && code.search(/grapes:/) === -1 && code.search(/strawberries:/) === -1);
`foods` should be an object.
```js
assert(typeof foods === 'object');
```
</section>
The `foods` object should have a key `"bananas"` with a value of `13`.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(foods.bananas === 13);
```
<div id='js-seed'>
The `foods` object should have a key `"grapes"` with a value of `35`.
```js
assert(foods.grapes === 35);
```
The `foods` object should have a key `"strawberries"` with a value of `27`.
```js
assert(foods.strawberries === 27);
```
The key-value pairs should be set using dot or bracket notation.
```js
assert(
code.search(/bananas:/) === -1 &&
code.search(/grapes:/) === -1 &&
code.search(/strawberries:/) === -1
);
```
# --seed--
## --seed-contents--
```js
let foods = {
@@ -96,14 +108,7 @@ let foods = {
console.log(foods);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
let foods = {
@@ -116,5 +121,3 @@ foods['bananas'] = 13;
foods['grapes'] = 35;
foods['strawberries'] = 27;
```
</section>

View File

@@ -5,9 +5,10 @@ challengeType: 1
forumTopicId: 301154
---
## Description
<section id='description'>
Since arrays can be changed, or <em>mutated</em>, at any time, there's no guarantee about where a particular piece of data will be on a given array, or if that element even still exists. Luckily, JavaScript provides us with another built-in method, <code>indexOf()</code>, that allows us to quickly and easily check for the presence of an element on an array. <code>indexOf()</code> takes an element as a parameter, and when called, it returns the position, or index, of that element, or <code>-1</code> if the element does not exist on the array.
# --description--
Since arrays can be changed, or *mutated*, at any time, there's no guarantee about where a particular piece of data will be on a given array, or if that element even still exists. Luckily, JavaScript provides us with another built-in method, `indexOf()`, that allows us to quickly and easily check for the presence of an element on an array. `indexOf()` takes an element as a parameter, and when called, it returns the position, or index, of that element, or `-1` if the element does not exist on the array.
For example:
```js
@@ -18,39 +19,57 @@ fruits.indexOf('oranges'); // returns 2
fruits.indexOf('pears'); // returns 1, the first index at which the element exists
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
<code>indexOf()</code> can be incredibly useful for quickly checking for the presence of an element on an array. We have defined a function, <code>quickCheck</code>, that takes an array and an element as arguments. Modify the function using <code>indexOf()</code> so that it returns <code>true</code> if the passed element exists on the array, and <code>false</code> if it does not.
</section>
`indexOf()` can be incredibly useful for quickly checking for the presence of an element on an array. We have defined a function, `quickCheck`, that takes an array and an element as arguments. Modify the function using `indexOf()` so that it returns `true` if the passed element exists on the array, and `false` if it does not.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: The <code>quickCheck</code> function should return a boolean (<code>true</code> or <code>false</code>), not a string (<code>"true"</code> or <code>"false"</code>)
testString: assert.isBoolean(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
- text: <code>quickCheck(["squash", "onions", "shallots"], "mushrooms")</code> should return <code>false</code>
testString: assert.strictEqual(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'), false);
- text: <code>quickCheck(["onions", "squash", "shallots"], "onions")</code> should return <code>true</code>
testString: assert.strictEqual(quickCheck(['onions', 'squash', 'shallots'], 'onions'), true);
- text: <code>quickCheck([3, 5, 9, 125, 45, 2], 125)</code> should return <code>true</code>
testString: assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true);
- text: <code>quickCheck([true, false, false], undefined)</code> should return <code>false</code>
testString: assert.strictEqual(quickCheck([true, false, false], undefined), false);
- text: The <code>quickCheck</code> function should utilize the <code>indexOf()</code> method
testString: assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1);
The `quickCheck` function should return a boolean (`true` or `false`), not a string (`"true"` or `"false"`)
```js
assert.isBoolean(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
```
</section>
`quickCheck(["squash", "onions", "shallots"], "mushrooms")` should return `false`
## Challenge Seed
<section id='challengeSeed'>
```js
assert.strictEqual(
quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'),
false
);
```
<div id='js-seed'>
`quickCheck(["onions", "squash", "shallots"], "onions")` should return `true`
```js
assert.strictEqual(
quickCheck(['onions', 'squash', 'shallots'], 'onions'),
true
);
```
`quickCheck([3, 5, 9, 125, 45, 2], 125)` should return `true`
```js
assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true);
```
`quickCheck([true, false, false], undefined)` should return `false`
```js
assert.strictEqual(quickCheck([true, false, false], undefined), false);
```
The `quickCheck` function should utilize the `indexOf()` method
```js
assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1);
```
# --seed--
## --seed-contents--
```js
function quickCheck(arr, elem) {
@@ -62,19 +81,10 @@ function quickCheck(arr, elem) {
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function quickCheck(arr, elem) {
return arr.indexOf(elem) >= 0;
}
```
</section>

View File

@@ -5,9 +5,9 @@ challengeType: 1
forumTopicId: 301155
---
## Description
<section id='description'>
Now we can add, modify, and remove keys from objects. But what if we just wanted to know if an object has a specific property? JavaScript provides us with two different ways to do this. One uses the <code>hasOwnProperty()</code> method and the other uses the <code>in</code> keyword. If we have an object <code>users</code> with a property of <code>Alan</code>, we could check for its presence in either of the following ways:
# --description--
Now we can add, modify, and remove keys from objects. But what if we just wanted to know if an object has a specific property? JavaScript provides us with two different ways to do this. One uses the `hasOwnProperty()` method and the other uses the `in` keyword. If we have an object `users` with a property of `Alan`, we could check for its presence in either of the following ways:
```js
users.hasOwnProperty('Alan');
@@ -15,38 +15,77 @@ users.hasOwnProperty('Alan');
// both return true
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
We've created an object, <code>users</code>, with some users in it and a function <code>isEveryoneHere</code>, which we pass the <code>users</code> object to as an argument. Finish writing this function so that it returns <code>true</code> only if the <code>users</code> object contains all four names, <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code>, as keys, and <code>false</code> otherwise.
</section>
We've created an object, `users`, with some users in it and a function `isEveryoneHere`, which we pass the `users` object to as an argument. Finish writing this function so that it returns `true` only if the `users` object contains all four names, `Alan`, `Jeff`, `Sarah`, and `Ryan`, as keys, and `false` otherwise.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: The <code>users</code> object should only contain the keys <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code>
testString: assert("Alan" in users && "Jeff" in users && "Sarah" in users && "Ryan" in users && Object.keys(users).length === 4);
- text: The function <code>isEveryoneHere</code> should return <code>true</code> if <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code> are properties on the <code>users</code> object
testString: assert(isEveryoneHere(users) === true);
- text: The function <code>isEveryoneHere</code> should return <code>false</code> if <code>Alan</code> is not a property on the <code>users</code> object
testString: assert((function() { delete users.Alan; return isEveryoneHere(users) })() === false);
- text: The function <code>isEveryoneHere</code> should return <code>false</code> if <code>Jeff</code> is not a property on the <code>users</code> object
testString: assert((function() { delete users.Jeff; return isEveryoneHere(users) })() === false);
- text: The function <code>isEveryoneHere</code> should return <code>false</code> if <code>Sarah</code> is not a property on the <code>users</code> object
testString: assert((function() { delete users.Sarah; return isEveryoneHere(users) })() === false);
- text: The function <code>isEveryoneHere</code> should return <code>false</code> if <code>Ryan</code> is not a property on the <code>users</code> object
testString: assert((function() { delete users.Ryan; return isEveryoneHere(users) })() === false);
The `users` object should only contain the keys `Alan`, `Jeff`, `Sarah`, and `Ryan`
```js
assert(
'Alan' in users &&
'Jeff' in users &&
'Sarah' in users &&
'Ryan' in users &&
Object.keys(users).length === 4
);
```
</section>
The function `isEveryoneHere` should return `true` if `Alan`, `Jeff`, `Sarah`, and `Ryan` are properties on the `users` object
## Challenge Seed
<section id='challengeSeed'>
```js
assert(isEveryoneHere(users) === true);
```
<div id='js-seed'>
The function `isEveryoneHere` should return `false` if `Alan` is not a property on the `users` object
```js
assert(
(function () {
delete users.Alan;
return isEveryoneHere(users);
})() === false
);
```
The function `isEveryoneHere` should return `false` if `Jeff` is not a property on the `users` object
```js
assert(
(function () {
delete users.Jeff;
return isEveryoneHere(users);
})() === false
);
```
The function `isEveryoneHere` should return `false` if `Sarah` is not a property on the `users` object
```js
assert(
(function () {
delete users.Sarah;
return isEveryoneHere(users);
})() === false
);
```
The function `isEveryoneHere` should return `false` if `Ryan` is not a property on the `users` object
```js
assert(
(function () {
delete users.Ryan;
return isEveryoneHere(users);
})() === false
);
```
# --seed--
## --seed-contents--
```js
let users = {
@@ -77,14 +116,7 @@ function isEveryoneHere(obj) {
console.log(isEveryoneHere(users));
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
let users = {
@@ -117,5 +149,3 @@ function isEveryoneHere(obj) {
console.log(isEveryoneHere(users));
```
</section>

View File

@@ -5,8 +5,8 @@ challengeType: 1
forumTopicId: 301156
---
## Description
<section id='description'>
# --description--
Another huge advantage of the <dfn>spread</dfn> operator, is the ability to combine arrays, or to insert all the elements of one array into another, at any index. With more traditional syntaxes, we can concatenate arrays, but this only allows us to combine arrays at the end of one, and at the start of another. Spread syntax makes the following operation extremely simple:
```js
@@ -17,31 +17,28 @@ let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];
```
Using spread syntax, we have just achieved an operation that would have been more complex and more verbose had we used traditional methods.
</section>
## Instructions
<section id='instructions'>
We have defined a function <code>spreadOut</code> that returns the variable <code>sentence</code>. Modify the function using the <dfn>spread</dfn> operator so that it returns the array <code>['learning', 'to', 'code', 'is', 'fun']</code>.
</section>
# --instructions--
## Tests
<section id='tests'>
We have defined a function `spreadOut` that returns the variable `sentence`. Modify the function using the <dfn>spread</dfn> operator so that it returns the array `['learning', 'to', 'code', 'is', 'fun']`.
```yml
tests:
- text: <code>spreadOut</code> should return <code>["learning", "to", "code", "is", "fun"]</code>
testString: assert.deepEqual(spreadOut(), ['learning', 'to', 'code', 'is', 'fun']);
- text: The <code>spreadOut</code> function should utilize spread syntax
testString: assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1);
# --hints--
`spreadOut` should return `["learning", "to", "code", "is", "fun"]`
```js
assert.deepEqual(spreadOut(), ['learning', 'to', 'code', 'is', 'fun']);
```
</section>
The `spreadOut` function should utilize spread syntax
## Challenge Seed
<section id='challengeSeed'>
```js
assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1);
```
<div id='js-seed'>
# --seed--
## --seed-contents--
```js
function spreadOut() {
@@ -53,14 +50,7 @@ function spreadOut() {
console.log(spreadOut());
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function spreadOut() {
@@ -68,7 +58,4 @@ function spreadOut() {
let sentence = ['learning', ...fragment, 'is', 'fun'];
return sentence;
}
```
</section>

View File

@@ -5,9 +5,10 @@ challengeType: 1
forumTopicId: 301157
---
## Description
<section id='description'>
While <code>slice()</code> allows us to be selective about what elements of an array to copy, among several other useful tasks, ES6's new <dfn>spread operator</dfn> allows us to easily copy <em>all</em> of an array's elements, in order, with a simple and highly readable syntax. The spread syntax simply looks like this: <code>...</code>
# --description--
While `slice()` allows us to be selective about what elements of an array to copy, among several other useful tasks, ES6's new <dfn>spread operator</dfn> allows us to easily copy *all* of an array's elements, in order, with a simple and highly readable syntax. The spread syntax simply looks like this: `...`
In practice, we can use the spread operator to copy an array like so:
```js
@@ -17,37 +18,58 @@ let thatArray = [...thisArray];
// thisArray remains unchanged and thatArray contains the same elements as thisArray
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
We have defined a function, <code>copyMachine</code> which takes <code>arr</code> (an array) and <code>num</code> (a number) as arguments. The function is supposed to return a new array made up of <code>num</code> copies of <code>arr</code>. We have done most of the work for you, but it doesn't work quite right yet. Modify the function using spread syntax so that it works correctly (hint: another method we have already covered might come in handy here!).
</section>
We have defined a function, `copyMachine` which takes `arr` (an array) and `num` (a number) as arguments. The function is supposed to return a new array made up of `num` copies of `arr`. We have done most of the work for you, but it doesn't work quite right yet. Modify the function using spread syntax so that it works correctly (hint: another method we have already covered might come in handy here!).
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: <code>copyMachine([true, false, true], 2)</code> should return <code>[[true, false, true], [true, false, true]]</code>
testString: assert.deepEqual(copyMachine([true, false, true], 2), [[true, false, true], [true, false, true]]);
- text: <code>copyMachine([1, 2, 3], 5)</code> should return <code>[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]</code>
testString: assert.deepEqual(copyMachine([1, 2, 3], 5), [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]);
- text: <code>copyMachine([true, true, null], 1)</code> should return <code>[[true, true, null]]</code>
testString: assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]]);
- text: <code>copyMachine(["it works"], 3)</code> should return <code>[["it works"], ["it works"], ["it works"]]</code>
testString: assert.deepEqual(copyMachine(['it works'], 3), [['it works'], ['it works'], ['it works']]);
- text: The <code>copyMachine</code> function should utilize the <code>spread operator</code> with array <code>arr</code>
testString: assert(__helpers.removeJSComments(code).match(/\.\.\.arr/));
`copyMachine([true, false, true], 2)` should return `[[true, false, true], [true, false, true]]`
```js
assert.deepEqual(copyMachine([true, false, true], 2), [
[true, false, true],
[true, false, true]
]);
```
</section>
`copyMachine([1, 2, 3], 5)` should return `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`
## Challenge Seed
<section id='challengeSeed'>
```js
assert.deepEqual(copyMachine([1, 2, 3], 5), [
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]
]);
```
<div id='js-seed'>
`copyMachine([true, true, null], 1)` should return `[[true, true, null]]`
```js
assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]]);
```
`copyMachine(["it works"], 3)` should return `[["it works"], ["it works"], ["it works"]]`
```js
assert.deepEqual(copyMachine(['it works'], 3), [
['it works'],
['it works'],
['it works']
]);
```
The `copyMachine` function should utilize the `spread operator` with array `arr`
```js
assert(__helpers.removeJSComments(code).match(/\.\.\.arr/));
```
# --seed--
## --seed-contents--
```js
function copyMachine(arr, num) {
@@ -64,23 +86,16 @@ function copyMachine(arr, num) {
console.log(copyMachine([true, false, true], 2));
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function copyMachine(arr,num){
let newArr=[];
while(num >=1){
newArr.push([...arr]);
num--;
}
return newArr;
let newArr=[];
while(num >=1){
newArr.push([...arr]);
num--;
}
return newArr;
}
console.log(copyMachine([true, false, true], 2));
```
</section>

View File

@@ -5,9 +5,9 @@ challengeType: 1
forumTopicId: 301158
---
## Description
<section id='description'>
The next method we will cover is <code>slice()</code>. Rather than modifying an array, <code>slice()</code> copies or <em>extracts</em> a given number of elements to a new array, leaving the array it is called upon untouched. <code>slice()</code> takes only 2 parameters &mdash; the first is the index at which to begin extraction, and the second is the index at which to stop extraction (extraction will occur up to, but not including the element at this index). Consider this:
# --description--
The next method we will cover is `slice()`. Rather than modifying an array, `slice()` copies or *extracts* a given number of elements to a new array, leaving the array it is called upon untouched. `slice()` takes only 2 parameters the first is the index at which to begin extraction, and the second is the index at which to stop extraction (extraction will occur up to, but not including the element at this index). Consider this:
```js
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
@@ -18,31 +18,31 @@ let todaysWeather = weatherConditions.slice(1, 3);
```
In effect, we have created a new array by extracting elements from an existing array.
</section>
## Instructions
<section id='instructions'>
We have defined a function, <code>forecast</code>, that takes an array as an argument. Modify the function using <code>slice()</code> to extract information from the argument array and return a new array that contains the elements <code>'warm'</code> and <code>'sunny'</code>.
</section>
# --instructions--
## Tests
<section id='tests'>
We have defined a function, `forecast`, that takes an array as an argument. Modify the function using `slice()` to extract information from the argument array and return a new array that contains the elements `'warm'` and `'sunny'`.
```yml
tests:
- text: <code>forecast</code> should return <code>["warm", "sunny"]</code>
testString: assert.deepEqual(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']), ['warm', 'sunny']);
- text: The <code>forecast</code> function should utilize the <code>slice()</code> method
testString: assert(/\.slice\(/.test(code));
# --hints--
`forecast` should return `["warm", "sunny"]`
```js
assert.deepEqual(
forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']),
['warm', 'sunny']
);
```
</section>
The `forecast` function should utilize the `slice()` method
## Challenge Seed
<section id='challengeSeed'>
```js
assert(/\.slice\(/.test(code));
```
<div id='js-seed'>
# --seed--
## --seed-contents--
```js
function forecast(arr) {
@@ -55,19 +55,10 @@ function forecast(arr) {
console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']));
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function forecast(arr) {
return arr.slice(2,4);
}
```
</section>

View File

@@ -5,9 +5,10 @@ challengeType: 1
forumTopicId: 301159
---
## Description
<section id='description'>
# --description--
Awesome! You have just learned a ton about arrays! This has been a fairly high level overview, and there is plenty more to learn about working with arrays, much of which you will see in later sections. But before moving on to looking at <dfn>Objects</dfn>, lets take one more look, and see how arrays can become a bit more complex than what we have seen in previous challenges.
One of the most powerful features when thinking of arrays as data structures, is that arrays can contain, or even be completely made up of other arrays. We have seen arrays that contain arrays in previous challenges, but fairly simple ones. However, arrays can contain an infinite depth of arrays that can contain other arrays, each with their own arbitrary levels of depth, and so on. In this way, an array can very quickly become very complex data structure, known as a <dfn>multi-dimensional</dfn>, or nested array. Consider the following example:
```js
@@ -29,8 +30,7 @@ let nestedArray = [ // top, or first level - the outer most array
];
```
While this example may seem convoluted, this level of complexity is not unheard of, or even unusual, when dealing with large amounts of data.
However, we can still very easily access the deepest levels of an array this complex with bracket notation:
While this example may seem convoluted, this level of complexity is not unheard of, or even unusual, when dealing with large amounts of data. However, we can still very easily access the deepest levels of an array this complex with bracket notation:
```js
console.log(nestedArray[2][1][0][0][0]);
@@ -46,37 +46,149 @@ console.log(nestedArray[2][1][0][0][0]);
// now logs: deeper still
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
We have defined a variable, <code>myNestedArray</code>, set equal to an array. Modify <code>myNestedArray</code>, using any combination of <dfn>strings</dfn>, <dfn>numbers</dfn>, and <dfn>booleans</dfn> for data elements, so that it has exactly five levels of depth (remember, the outer-most array is level 1). Somewhere on the third level, include the string <code>'deep'</code>, on the fourth level, include the string <code>'deeper'</code>, and on the fifth level, include the string <code>'deepest'</code>.
</section>
We have defined a variable, `myNestedArray`, set equal to an array. Modify `myNestedArray`, using any combination of <dfn>strings</dfn>, <dfn>numbers</dfn>, and <dfn>booleans</dfn> for data elements, so that it has exactly five levels of depth (remember, the outer-most array is level 1). Somewhere on the third level, include the string `'deep'`, on the fourth level, include the string `'deeper'`, and on the fifth level, include the string `'deepest'`.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: <code>myNestedArray</code> should contain only numbers, booleans, and strings as data elements
testString: 'assert.strictEqual((function(arr) { let flattened = (function flatten(arr) { const flat = [].concat(...arr); return flat.some (Array.isArray) ? flatten(flat) : flat; })(arr); for (let i = 0; i < flattened.length; i++) { if ( typeof flattened[i] !== ''number'' && typeof flattened[i] !== ''string'' && typeof flattened[i] !== ''boolean'') { return false } } return true })(myNestedArray), true);'
- text: <code>myNestedArray</code> should have exactly 5 levels of depth
testString: 'assert.strictEqual((function(arr) {let depth = 0;function arrayDepth(array, i, d) { if (Array.isArray(array[i])) { arrayDepth(array[i], 0, d + 1);} else { depth = (d > depth) ? d : depth;}if (i < array.length) { arrayDepth(array, i + 1, d);} }arrayDepth(arr, 0, 0);return depth;})(myNestedArray), 4);'
- text: <code>myNestedArray</code> should contain exactly one occurrence of the string <code>"deep"</code> on an array nested 3 levels deep
testString: assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deep').length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deep')[0] === 2);
- text: <code>myNestedArray</code> should contain exactly one occurrence of the string <code>"deeper"</code> on an array nested 4 levels deep
testString: assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deeper').length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deeper')[0] === 3);
- text: <code>myNestedArray</code> should contain exactly one occurrence of the string <code>"deepest"</code> on an array nested 5 levels deep
testString: assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deepest').length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, 'deepest')[0] === 4);
`myNestedArray` should contain only numbers, booleans, and strings as data elements
```js
assert.strictEqual(
(function (arr) {
let flattened = (function flatten(arr) {
const flat = [].concat(...arr);
return flat.some(Array.isArray) ? flatten(flat) : flat;
})(arr);
for (let i = 0; i < flattened.length; i++) {
if (
typeof flattened[i] !== 'number' &&
typeof flattened[i] !== 'string' &&
typeof flattened[i] !== 'boolean'
) {
return false;
}
}
return true;
})(myNestedArray),
true
);
```
</section>
`myNestedArray` should have exactly 5 levels of depth
## Challenge Seed
<section id='challengeSeed'>
```js
assert.strictEqual(
(function (arr) {
let depth = 0;
function arrayDepth(array, i, d) {
if (Array.isArray(array[i])) {
arrayDepth(array[i], 0, d + 1);
} else {
depth = d > depth ? d : depth;
}
if (i < array.length) {
arrayDepth(array, i + 1, d);
}
}
arrayDepth(arr, 0, 0);
return depth;
})(myNestedArray),
4
);
```
<div id='js-seed'>
`myNestedArray` should contain exactly one occurrence of the string `"deep"` on an array nested 3 levels deep
```js
assert(
(function howDeep(array, target, depth = 0) {
return array.reduce((combined, current) => {
if (Array.isArray(current)) {
return combined.concat(howDeep(current, target, depth + 1));
} else if (current === target) {
return combined.concat(depth);
} else {
return combined;
}
}, []);
})(myNestedArray, 'deep').length === 1 &&
(function howDeep(array, target, depth = 0) {
return array.reduce((combined, current) => {
if (Array.isArray(current)) {
return combined.concat(howDeep(current, target, depth + 1));
} else if (current === target) {
return combined.concat(depth);
} else {
return combined;
}
}, []);
})(myNestedArray, 'deep')[0] === 2
);
```
`myNestedArray` should contain exactly one occurrence of the string `"deeper"` on an array nested 4 levels deep
```js
assert(
(function howDeep(array, target, depth = 0) {
return array.reduce((combined, current) => {
if (Array.isArray(current)) {
return combined.concat(howDeep(current, target, depth + 1));
} else if (current === target) {
return combined.concat(depth);
} else {
return combined;
}
}, []);
})(myNestedArray, 'deeper').length === 1 &&
(function howDeep(array, target, depth = 0) {
return array.reduce((combined, current) => {
if (Array.isArray(current)) {
return combined.concat(howDeep(current, target, depth + 1));
} else if (current === target) {
return combined.concat(depth);
} else {
return combined;
}
}, []);
})(myNestedArray, 'deeper')[0] === 3
);
```
`myNestedArray` should contain exactly one occurrence of the string `"deepest"` on an array nested 5 levels deep
```js
assert(
(function howDeep(array, target, depth = 0) {
return array.reduce((combined, current) => {
if (Array.isArray(current)) {
return combined.concat(howDeep(current, target, depth + 1));
} else if (current === target) {
return combined.concat(depth);
} else {
return combined;
}
}, []);
})(myNestedArray, 'deepest').length === 1 &&
(function howDeep(array, target, depth = 0) {
return array.reduce((combined, current) => {
if (Array.isArray(current)) {
return combined.concat(howDeep(current, target, depth + 1));
} else if (current === target) {
return combined.concat(depth);
} else {
return combined;
}
}, []);
})(myNestedArray, 'deepest')[0] === 4
);
```
# --seed--
## --seed-contents--
```js
let myNestedArray = [
@@ -90,14 +202,7 @@ let myNestedArray = [
];
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
let myNestedArray = [
@@ -108,5 +213,3 @@ let myNestedArray = [
['iterate', 1.3849, 7, '8.4876', 'arbitrary', 'depth']
];
```
</section>

View File

@@ -5,34 +5,51 @@ challengeType: 1
forumTopicId: 301160
---
## Description
<section id='description'>
We can also generate an array which contains all the keys stored in an object using the <code>Object.keys()</code> method and passing in an object as the argument. This will return an array with strings representing each property in the object. Again, there will be no specific order to the entries in the array.
</section>
# --description--
## Instructions
<section id='instructions'>
Finish writing the <code>getArrayOfUsers</code> function so that it returns an array containing all the properties in the object it receives as an argument.
</section>
We can also generate an array which contains all the keys stored in an object using the `Object.keys()` method and passing in an object as the argument. This will return an array with strings representing each property in the object. Again, there will be no specific order to the entries in the array.
## Tests
<section id='tests'>
# --instructions--
```yml
tests:
- text: The <code>users</code> object should only contain the keys <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code>
testString: assert('Alan' in users && 'Jeff' in users && 'Sarah' in users && 'Ryan' in users && Object.keys(users).length === 4);
- text: The <code>getArrayOfUsers</code> function should return an array which contains all the keys in the <code>users</code> object
testString: assert((function() { users.Sam = {}; users.Lewis = {}; let R = getArrayOfUsers(users); return (R.indexOf('Alan') !== -1 && R.indexOf('Jeff') !== -1 && R.indexOf('Sarah') !== -1 && R.indexOf('Ryan') !== -1 && R.indexOf('Sam') !== -1 && R.indexOf('Lewis') !== -1); })() === true);
Finish writing the `getArrayOfUsers` function so that it returns an array containing all the properties in the object it receives as an argument.
# --hints--
The `users` object should only contain the keys `Alan`, `Jeff`, `Sarah`, and `Ryan`
```js
assert(
'Alan' in users &&
'Jeff' in users &&
'Sarah' in users &&
'Ryan' in users &&
Object.keys(users).length === 4
);
```
</section>
The `getArrayOfUsers` function should return an array which contains all the keys in the `users` object
## Challenge Seed
<section id='challengeSeed'>
```js
assert(
(function () {
users.Sam = {};
users.Lewis = {};
let R = getArrayOfUsers(users);
return (
R.indexOf('Alan') !== -1 &&
R.indexOf('Jeff') !== -1 &&
R.indexOf('Sarah') !== -1 &&
R.indexOf('Ryan') !== -1 &&
R.indexOf('Sam') !== -1 &&
R.indexOf('Lewis') !== -1
);
})() === true
);
```
<div id='js-seed'>
# --seed--
## --seed-contents--
```js
let users = {
@@ -63,14 +80,7 @@ function getArrayOfUsers(obj) {
console.log(getArrayOfUsers(users));
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
let users = {
@@ -98,5 +108,3 @@ function getArrayOfUsers(obj) {
console.log(getArrayOfUsers(users));
```
</section>

View File

@@ -5,9 +5,10 @@ challengeType: 1
forumTopicId: 301161
---
## Description
<section id='description'>
Sometimes when working with arrays, it is very handy to be able to iterate through each item to find one or more elements that we might need, or to manipulate an array based on which data items meet a certain set of criteria. JavaScript offers several built in methods that each iterate over arrays in slightly different ways to achieve different results (such as <code>every()</code>, <code>forEach()</code>, <code>map()</code>, etc.), however the technique which is most flexible and offers us the greatest amount of control is a simple <code>for</code> loop.
# --description--
Sometimes when working with arrays, it is very handy to be able to iterate through each item to find one or more elements that we might need, or to manipulate an array based on which data items meet a certain set of criteria. JavaScript offers several built in methods that each iterate over arrays in slightly different ways to achieve different results (such as `every()`, `forEach()`, `map()`, etc.), however the technique which is most flexible and offers us the greatest amount of control is a simple `for` loop.
Consider the following:
```js
@@ -25,38 +26,90 @@ greaterThanTen([2, 12, 8, 14, 80, 0, 1]);
// returns [12, 14, 80]
```
Using a <code>for</code> loop, this function iterates through and accesses each element of the array, and subjects it to a simple test that we have created. In this way, we have easily and programmatically determined which data items are greater than <code>10</code>, and returned a new array containing those items.
</section>
Using a `for` loop, this function iterates through and accesses each element of the array, and subjects it to a simple test that we have created. In this way, we have easily and programmatically determined which data items are greater than `10`, and returned a new array containing those items.
## Instructions
<section id='instructions'>
We have defined a function, <code>filteredArray</code>, which takes <code>arr</code>, a nested array, and <code>elem</code> as arguments, and returns a new array. <code>elem</code> represents an element that may or may not be present on one or more of the arrays nested within <code>arr</code>. Modify the function, using a <code>for</code> loop, to return a filtered version of the passed array such that any array nested within <code>arr</code> containing <code>elem</code> has been removed.
</section>
# --instructions--
## Tests
<section id='tests'>
We have defined a function, `filteredArray`, which takes `arr`, a nested array, and `elem` as arguments, and returns a new array. `elem` represents an element that may or may not be present on one or more of the arrays nested within `arr`. Modify the function, using a `for` loop, to return a filtered version of the passed array such that any array nested within `arr` containing `elem` has been removed.
```yml
tests:
- text: <code>filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)</code> should return <code>[ [10, 8, 3], [14, 6, 23] ]</code>
testString: assert.deepEqual(filteredArray([ [10, 8, 3], [14, 6, 23], [3, 18, 6] ], 18), [[10, 8, 3], [14, 6, 23]]);
- text: <code>filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)</code> should return <code>[ ["flutes", 4] ]</code>
testString: assert.deepEqual(filteredArray([ ['trumpets', 2], ['flutes', 4], ['saxophones', 2] ], 2), [['flutes', 4]]);
- text: <code>filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")</code> should return <code>[ ["amy", "beth", "sam"] ]</code>
testString: assert.deepEqual(filteredArray([['amy', 'beth', 'sam'], ['dave', 'sean', 'peter']], 'peter'), [['amy', 'beth', 'sam']]);
- text: <code>filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)</code> should return <code>[ ]</code>
testString: assert.deepEqual(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3), []);
- text: The <code>filteredArray</code> function should utilize a <code>for</code> loop
testString: assert.notStrictEqual(filteredArray.toString().search(/for/), -1);
# --hints--
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` should return `[ [10, 8, 3], [14, 6, 23] ]`
```js
assert.deepEqual(
filteredArray(
[
[10, 8, 3],
[14, 6, 23],
[3, 18, 6]
],
18
),
[
[10, 8, 3],
[14, 6, 23]
]
);
```
</section>
`filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)` should return `[ ["flutes", 4] ]`
## Challenge Seed
<section id='challengeSeed'>
```js
assert.deepEqual(
filteredArray(
[
['trumpets', 2],
['flutes', 4],
['saxophones', 2]
],
2
),
[['flutes', 4]]
);
```
<div id='js-seed'>
`filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")` should return `[ ["amy", "beth", "sam"] ]`
```js
assert.deepEqual(
filteredArray(
[
['amy', 'beth', 'sam'],
['dave', 'sean', 'peter']
],
'peter'
),
[['amy', 'beth', 'sam']]
);
```
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` should return `[ ]`
```js
assert.deepEqual(
filteredArray(
[
[3, 2, 3],
[1, 6, 3],
[3, 13, 26],
[19, 3, 9]
],
3
),
[]
);
```
The `filteredArray` function should utilize a `for` loop
```js
assert.notStrictEqual(filteredArray.toString().search(/for/), -1);
```
# --seed--
## --seed-contents--
```js
function filteredArray(arr, elem) {
@@ -70,14 +123,7 @@ function filteredArray(arr, elem) {
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function filteredArray(arr, elem) {
@@ -90,5 +136,3 @@ function filteredArray(arr, elem) {
return newArr;
}
```
</section>

View File

@@ -1,14 +1,13 @@
---
id: 587d7b7d367417b2b2512b1d
title: 'Iterate Through the Keys of an Object with a for...in Statement'
title: Iterate Through the Keys of an Object with a for...in Statement
challengeType: 1
forumTopicId: 301162
---
## Description
<section id='description'>
# --description--
Sometimes you may need to iterate through all the keys within an object. This requires a specific syntax in JavaScript called a <dfn>for...in</dfn> statement. For our <code>users</code> object, this could look like:
Sometimes you may need to iterate through all the keys within an object. This requires a specific syntax in JavaScript called a <dfn>for...in</dfn> statement. For our `users` object, this could look like:
```js
for (let user in users) {
@@ -22,15 +21,11 @@ Sarah
Ryan
```
In this statement, we defined a variable <code>user</code>, and as you can see, this variable was reset during each iteration to each of the object's keys as the statement looped through the object, resulting in each user's name being printed to the console.
<strong>NOTE:</strong> Objects do not maintain an ordering to stored keys like arrays do; thus a key's position on an object, or the relative order in which it appears, is irrelevant when referencing or accessing that key.
</section>
In this statement, we defined a variable `user`, and as you can see, this variable was reset during each iteration to each of the object's keys as the statement looped through the object, resulting in each user's name being printed to the console. **NOTE:** Objects do not maintain an ordering to stored keys like arrays do; thus a key's position on an object, or the relative order in which it appears, is irrelevant when referencing or accessing that key.
## Instructions
<section id='instructions'>
We've defined a function <code>countOnline</code> which accepts one argument (a users object). Use a <dfn>for...in</dfn> statement within this function to loop through the users object passed into the function and return the number of users whose <code>online</code> property is set to <code>true</code>. An example of a users object which could be passed to <code>countOnline</code> is shown below. Each user will have an <code>online</code> property with either a <code>true</code> or <code>false</code> value.
# --instructions--
We've defined a function `countOnline` which accepts one argument (a users object). Use a <dfn>for...in</dfn> statement within this function to loop through the users object passed into the function and return the number of users whose `online` property is set to `true`. An example of a users object which could be passed to `countOnline` is shown below. Each user will have an `online` property with either a `true` or `false` value.
```js
{
@@ -46,42 +41,39 @@ We've defined a function <code>countOnline</code> which accepts one argument (a
}
```
</section>
# --hints--
## Tests
<section id='tests'>
```yml
tests:
- text: The function <code>countOnline</code> should use a `for in` statement to iterate through the object keys of the object passed to it.
testString: assert(code.match(/for\s*\(\s*(var|let|const)\s+[a-zA-Z_$]\w*\s+in\s+[a-zA-Z_$]\w*\s*\)\s*{/));
- text: 'The function <code>countOnline</code> should return <code>1</code> when the object <code>{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }</code> is passed to it'
testString: assert(countOnline(usersObj1) === 1);
- text: 'The function <code>countOnline</code> should return <code>2</code> when the object <code>{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }</code> is passed to it'
testString: assert(countOnline(usersObj2) === 2);
- text: 'The function <code>countOnline</code> should return <code>0</code> when the object <code>{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }</code> is passed to it'
testString: assert(countOnline(usersObj3) === 0);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
The function `countOnline` should use a `for in` statement to iterate through the object keys of the object passed to it.
```js
function countOnline(usersObj) {
// Only change code below this line
// Only change code above this line
}
assert(
code.match(
/for\s*\(\s*(var|let|const)\s+[a-zA-Z_$]\w*\s+in\s+[a-zA-Z_$]\w*\s*\)\s*{/
)
);
```
</div>
The function `countOnline` should return `1` when the object `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` is passed to it
### After Test
<div id='js-teardown'>
```js
assert(countOnline(usersObj1) === 1);
```
The function `countOnline` should return `2` when the object `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` is passed to it
```js
assert(countOnline(usersObj2) === 2);
```
The function `countOnline` should return `0` when the object `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` is passed to it
```js
assert(countOnline(usersObj3) === 0);
```
# --seed--
## --after-user-code--
```js
const usersObj1 = {
@@ -122,16 +114,19 @@ const usersObj3 = {
}
```
</div>
</section>
## Solution
<section id='solution'>
## --seed-contents--
```js
function countOnline(usersObj) {
// Only change code below this line
// Only change code above this line
}
```
# --solutions--
```js
function countOnline(usersObj) {
let online = 0;
for(let user in usersObj){
@@ -141,7 +136,4 @@ function countOnline(usersObj) {
}
return online;
}
```
</section>

View File

@@ -5,36 +5,51 @@ challengeType: 1
forumTopicId: 301163
---
## Description
<section id='description'>
# --description--
Now you've seen all the basic operations for JavaScript objects. You can add, modify, and remove key-value pairs, check if keys exist, and iterate over all the keys in an object. As you continue learning JavaScript you will see even more versatile applications of objects. Additionally, the Data Structures lessons located in the Coding Interview Prep section of the curriculum also cover the ES6 <dfn>Map</dfn> and <dfn>Set</dfn> objects, both of which are similar to ordinary objects but provide some additional features. Now that you've learned the basics of arrays and objects, you're fully prepared to begin tackling more complex problems using JavaScript!
</section>
## Instructions
<section id='instructions'>
Take a look at the object we've provided in the code editor. The <code>user</code> object contains three keys. The <code>data</code> key contains five keys, one of which contains an array of <code>friends</code>. From this, you can see how flexible objects are as data structures. We've started writing a function <code>addFriend</code>. Finish writing it so that it takes a <code>user</code> object and adds the name of the <code>friend</code> argument to the array stored in <code>user.data.friends</code> and returns that array.
</section>
# --instructions--
## Tests
<section id='tests'>
Take a look at the object we've provided in the code editor. The `user` object contains three keys. The `data` key contains five keys, one of which contains an array of `friends`. From this, you can see how flexible objects are as data structures. We've started writing a function `addFriend`. Finish writing it so that it takes a `user` object and adds the name of the `friend` argument to the array stored in `user.data.friends` and returns that array.
```yml
tests:
- text: The <code>user</code> object should have <code>name</code>, <code>age</code>, and <code>data</code> keys.
testString: assert('name' in user && 'age' in user && 'data' in user);
- text: The <code>addFriend</code> function should accept a <code>user</code> object and a <code>friend</code> string as arguments and add the friend to the array of <code>friends</code> in the <code>user</code> object.
testString: assert((function() { let L1 = user.data.friends.length; addFriend(user, 'Sean'); let L2 = user.data.friends.length; return (L2 === L1 + 1); })());
- text: <code>addFriend(user, "Pete")</code> should return <code>["Sam", "Kira", "Tomo", "Pete"]</code>.
testString: assert.deepEqual((function() { delete user.data.friends; user.data.friends = ['Sam', 'Kira', 'Tomo']; return addFriend(user, 'Pete') })(), ['Sam', 'Kira', 'Tomo', 'Pete']);
# --hints--
The `user` object should have `name`, `age`, and `data` keys.
```js
assert('name' in user && 'age' in user && 'data' in user);
```
</section>
The `addFriend` function should accept a `user` object and a `friend` string as arguments and add the friend to the array of `friends` in the `user` object.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(
(function () {
let L1 = user.data.friends.length;
addFriend(user, 'Sean');
let L2 = user.data.friends.length;
return L2 === L1 + 1;
})()
);
```
<div id='js-seed'>
`addFriend(user, "Pete")` should return `["Sam", "Kira", "Tomo", "Pete"]`.
```js
assert.deepEqual(
(function () {
delete user.data.friends;
user.data.friends = ['Sam', 'Kira', 'Tomo'];
return addFriend(user, 'Pete');
})(),
['Sam', 'Kira', 'Tomo', 'Pete']
);
```
# --seed--
## --seed-contents--
```js
let user = {
@@ -66,14 +81,7 @@ function addFriend(userObj, friend) {
console.log(addFriend(user, 'Pete'));
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
let user = {
@@ -101,5 +109,3 @@ function addFriend(userObj, friend) {
return userObj.data.friends;
}
```
</section>

View File

@@ -5,8 +5,8 @@ challengeType: 1
forumTopicId: 301164
---
## Description
<section id='description'>
# --description--
Now let's take a look at a slightly more complex object. Object properties can be nested to an arbitrary depth, and their values can be any type of data supported by JavaScript, including arrays and even other objects. Consider the following:
```js
@@ -25,41 +25,47 @@ let nestedObject = {
};
```
<code>nestedObject</code> has three properties: <code>id</code> (value is a number), <code>date</code> (value is a string), and <code>data</code> (value is an object with its nested structure). While structures can quickly become complex, we can still use the same notations to access the information we need. To assign the value <code>10</code> to the <code>busy</code> property of the nested <code>onlineStatus</code> object, we use dot notation to reference the property:
`nestedObject` has three properties: `id` (value is a number), `date` (value is a string), and `data` (value is an object with its nested structure). While structures can quickly become complex, we can still use the same notations to access the information we need. To assign the value `10` to the `busy` property of the nested `onlineStatus` object, we use dot notation to reference the property:
```js
nestedObject.data.onlineStatus.busy = 10;
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
Here we've defined an object <code>userActivity</code>, which includes another object nested within it. Set the value of the <code>online</code> key to <code>45</code>.
</section>
Here we've defined an object `userActivity`, which includes another object nested within it. Set the value of the `online` key to `45`.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: <code>userActivity</code> should have <code>id</code>, <code>date</code> and <code>data</code> properties.
testString: assert('id' in userActivity && 'date' in userActivity && 'data' in userActivity);
- text: <code>userActivity</code> should have a <code>data</code> key set to an object with keys <code>totalUsers</code> and <code>online</code>.
testString: assert('totalUsers' in userActivity.data && 'online' in userActivity.data);
- text: The <code>online</code> property nested in the <code>data</code> key of <code>userActivity</code> should be set to <code>45</code>
testString: assert(userActivity.data.online === 45);
- text: The <code>online</code> property should be set using dot or bracket notation.
testString: 'assert.strictEqual(code.search(/online: 45/), -1);'
`userActivity` should have `id`, `date` and `data` properties.
```js
assert(
'id' in userActivity && 'date' in userActivity && 'data' in userActivity
);
```
</section>
`userActivity` should have a `data` key set to an object with keys `totalUsers` and `online`.
## Challenge Seed
<section id='challengeSeed'>
```js
assert('totalUsers' in userActivity.data && 'online' in userActivity.data);
```
<div id='js-seed'>
The `online` property nested in the `data` key of `userActivity` should be set to `45`
```js
assert(userActivity.data.online === 45);
```
The `online` property should be set using dot or bracket notation.
```js
assert.strictEqual(code.search(/online: 45/), -1);
```
# --seed--
## --seed-contents--
```js
let userActivity = {
@@ -78,14 +84,7 @@ let userActivity = {
console.log(userActivity);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
let userActivity = {
@@ -99,5 +98,3 @@ let userActivity = {
userActivity.data.online = 45;
```
</section>

View File

@@ -5,9 +5,10 @@ challengeType: 1
forumTopicId: 301165
---
## Description
<section id='description'>
Both <code>push()</code> and <code>unshift()</code> have corresponding methods that are nearly functional opposites: <code>pop()</code> and <code>shift()</code>. As you may have guessed by now, instead of adding, <code>pop()</code> <em>removes</em> an element from the end of an array, while <code>shift()</code> removes an element from the beginning. The key difference between <code>pop()</code> and <code>shift()</code> and their cousins <code>push()</code> and <code>unshift()</code>, is that neither method takes parameters, and each only allows an array to be modified by a single element at a time.
# --description--
Both `push()` and `unshift()` have corresponding methods that are nearly functional opposites: `pop()` and `shift()`. As you may have guessed by now, instead of adding, `pop()` *removes* an element from the end of an array, while `shift()` removes an element from the beginning. The key difference between `pop()` and `shift()` and their cousins `push()` and `unshift()`, is that neither method takes parameters, and each only allows an array to be modified by a single element at a time.
Let's take a look:
```js
@@ -28,33 +29,36 @@ let popped = greetings.pop();
// greetings now equals []
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
We have defined a function, <code>popShift</code>, which takes an array as an argument and returns a new array. Modify the function, using <code>pop()</code> and <code>shift()</code>, to remove the first and last elements of the argument array, and assign the removed elements to their corresponding variables, so that the returned array contains their values.
</section>
We have defined a function, `popShift`, which takes an array as an argument and returns a new array. Modify the function, using `pop()` and `shift()`, to remove the first and last elements of the argument array, and assign the removed elements to their corresponding variables, so that the returned array contains their values.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: <code>popShift(["challenge", "is", "not", "complete"])</code> should return <code>["challenge", "complete"]</code>
testString: assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), ["challenge", "complete"]);
- text: The <code>popShift</code> function should utilize the <code>pop()</code> method
testString: assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1);
- text: The <code>popShift</code> function should utilize the <code>shift()</code> method
testString: assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1);
`popShift(["challenge", "is", "not", "complete"])` should return `["challenge", "complete"]`
```js
assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
'challenge',
'complete'
]);
```
</section>
The `popShift` function should utilize the `pop()` method
## Challenge Seed
<section id='challengeSeed'>
```js
assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1);
```
<div id='js-seed'>
The `popShift` function should utilize the `shift()` method
```js
assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1);
```
# --seed--
## --seed-contents--
```js
function popShift(arr) {
@@ -66,14 +70,7 @@ function popShift(arr) {
console.log(popShift(['challenge', 'is', 'not', 'complete']));
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function popShift(arr) {
@@ -82,5 +79,3 @@ function popShift(arr) {
return [shifted, popped];
}
```
</section>

View File

@@ -5,10 +5,11 @@ challengeType: 1
forumTopicId: 301166
---
## Description
<section id='description'>
Ok, so we've learned how to remove elements from the beginning and end of arrays using <code>shift()</code> and <code>pop()</code>, but what if we want to remove an element from somewhere in the middle? Or remove more than one element at once? Well, that's where <code>splice()</code> comes in. <code>splice()</code> allows us to do just that: <strong>remove any number of consecutive elements</strong> from anywhere in an array.
<code>splice()</code> can take up to 3 parameters, but for now, we'll focus on just the first 2. The first two parameters of <code>splice()</code> are integers which represent indexes, or positions, of the array that <code>splice()</code> is being called upon. And remember, arrays are <em>zero-indexed</em>, so to indicate the first element of an array, we would use <code>0</code>. <code>splice()</code>'s first parameter represents the index on the array from which to begin removing elements, while the second parameter indicates the number of elements to delete. For example:
# --description--
Ok, so we've learned how to remove elements from the beginning and end of arrays using `shift()` and `pop()`, but what if we want to remove an element from somewhere in the middle? Or remove more than one element at once? Well, that's where `splice()` comes in. `splice()` allows us to do just that: **remove any number of consecutive elements** from anywhere in an array.
`splice()` can take up to 3 parameters, but for now, we'll focus on just the first 2. The first two parameters of `splice()` are integers which represent indexes, or positions, of the array that `splice()` is being called upon. And remember, arrays are *zero-indexed*, so to indicate the first element of an array, we would use `0`. `splice()`'s first parameter represents the index on the array from which to begin removing elements, while the second parameter indicates the number of elements to delete. For example:
```js
let array = ['today', 'was', 'not', 'so', 'great'];
@@ -18,7 +19,7 @@ array.splice(2, 2);
// array now equals ['today', 'was', 'great']
```
<code>splice()</code> not only modifies the array it's being called on, but it also returns a new array containing the value of the removed elements:
`splice()` not only modifies the array it's being called on, but it also returns a new array containing the value of the removed elements:
```js
let array = ['I', 'am', 'feeling', 'really', 'happy'];
@@ -27,36 +28,46 @@ let newArray = array.splice(3, 2);
// newArray equals ['really', 'happy']
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
We've initialized an array `arr`. Use `splice()` to remove elements from `arr`, so that it only contains elements that sum to the value of `10`.
We've initialized an array `arr`. Use `splice()` to remove elements from `arr`, so that it only contains elements that sum to the value of <code>10</code>.
# --hints--
</section>
You should not change the original line of `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`.
## Tests
<section id='tests'>
```yml
tests:
- text: You should not change the original line of <code>const arr = [2, 4, 5, 1, 7, 5, 2, 1];</code>.
testString: assert(__helpers.removeWhiteSpace(code).match(/constarr=\[2,4,5,1,7,5,2,1\];?/));
- text: <code>arr</code> should only contain elements that sum to <code>10</code>.
testString: assert.strictEqual(arr.reduce((a, b) => a + b), 10);
- text: Your code should utilize the <code>splice()</code> method on <code>arr</code>.
testString: assert(__helpers.removeWhiteSpace(code).match(/arr\.splice\(/));
- text: The splice should only remove elements from <code>arr</code> and not add any additional elements to <code>arr</code>.
testString: assert(!__helpers.removeWhiteSpace(code).match(/arr\.splice\(\d+,\d+,\d+.*\)/g));
```js
assert(
__helpers.removeWhiteSpace(code).match(/constarr=\[2,4,5,1,7,5,2,1\];?/)
);
```
</section>
`arr` should only contain elements that sum to `10`.
## Challenge Seed
<section id='challengeSeed'>
```js
assert.strictEqual(
arr.reduce((a, b) => a + b),
10
);
```
<div id='js-seed'>
Your code should utilize the `splice()` method on `arr`.
```js
assert(__helpers.removeWhiteSpace(code).match(/arr\.splice\(/));
```
The splice should only remove elements from `arr` and not add any additional elements to `arr`.
```js
assert(
!__helpers.removeWhiteSpace(code).match(/arr\.splice\(\d+,\d+,\d+.*\)/g)
);
```
# --seed--
## --seed-contents--
```js
const arr = [2, 4, 5, 1, 7, 5, 2, 1];
@@ -66,18 +77,9 @@ const arr = [2, 4, 5, 1, 7, 5, 2, 1];
console.log(arr);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
const arr = [2, 4, 5, 1, 7, 5, 2, 1];
arr.splice(1, 4);
```
</section>

View File

@@ -5,8 +5,8 @@ challengeType: 1
forumTopicId: 301167
---
## Description
<section id='description'>
# --description--
The below is an example of the simplest implementation of an array data structure. This is known as a <dfn>one-dimensional array</dfn>, meaning it only has one level, or that it does not have any other arrays nested within it. Notice it contains <dfn>booleans</dfn>, <dfn>strings</dfn>, and <dfn>numbers</dfn>, among other valid JavaScript data types:
```js
@@ -15,8 +15,7 @@ console.log(simpleArray.length);
// logs 7
```
All arrays have a length property, which as shown above, can be very easily accessed with the syntax <code>Array.length</code>.
A more complex implementation of an array can be seen below. This is known as a <dfn>multi-dimensional array</dfn>, or an array that contains other arrays. Notice that this array also contains JavaScript <dfn>objects</dfn>, which we will examine very closely in our next section, but for now, all you need to know is that arrays are also capable of storing complex objects.
All arrays have a length property, which as shown above, can be very easily accessed with the syntax `Array.length`. A more complex implementation of an array can be seen below. This is known as a <dfn>multi-dimensional array</dfn>, or an array that contains other arrays. Notice that this array also contains JavaScript <dfn>objects</dfn>, which we will examine very closely in our next section, but for now, all you need to know is that arrays are also capable of storing complex objects.
```js
let complexArray = [
@@ -43,53 +42,52 @@ let complexArray = [
];
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
We have defined a variable called <code>yourArray</code>. Complete the statement by assigning an array of at least 5 elements in length to the <code>yourArray</code> variable. Your array should contain at least one <dfn>string</dfn>, one <dfn>number</dfn>, and one <dfn>boolean</dfn>.
</section>
We have defined a variable called `yourArray`. Complete the statement by assigning an array of at least 5 elements in length to the `yourArray` variable. Your array should contain at least one <dfn>string</dfn>, one <dfn>number</dfn>, and one <dfn>boolean</dfn>.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: <code>yourArray</code> should be an array.
testString: assert.strictEqual(Array.isArray(yourArray), true);
- text: <code>yourArray</code> should be at least 5 elements long.
testString: assert.isAtLeast(yourArray.length, 5);
- text: <code>yourArray</code> should contain at least one <code>boolean</code>.
testString: assert(yourArray.filter( el => typeof el === 'boolean').length >= 1);
- text: <code>yourArray</code> should contain at least one <code>number</code>.
testString: assert(yourArray.filter( el => typeof el === 'number').length >= 1);
- text: <code>yourArray</code> should contain at least one <code>string</code>.
testString: assert(yourArray.filter( el => typeof el === 'string').length >= 1);
`yourArray` should be an array.
```js
assert.strictEqual(Array.isArray(yourArray), true);
```
</section>
`yourArray` should be at least 5 elements long.
## Challenge Seed
<section id='challengeSeed'>
```js
assert.isAtLeast(yourArray.length, 5);
```
<div id='js-seed'>
`yourArray` should contain at least one `boolean`.
```js
assert(yourArray.filter((el) => typeof el === 'boolean').length >= 1);
```
`yourArray` should contain at least one `number`.
```js
assert(yourArray.filter((el) => typeof el === 'number').length >= 1);
```
`yourArray` should contain at least one `string`.
```js
assert(yourArray.filter((el) => typeof el === 'string').length >= 1);
```
# --seed--
## --seed-contents--
```js
let yourArray; // Change this line
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
let yourArray = ['a string', 100, true, ['one', 2], 'another string'];
```
</section>

View File

@@ -5,41 +5,48 @@ challengeType: 1
forumTopicId: 301168
---
## Description
<section id='description'>
Now you know what objects are and their basic features and advantages. In short, they are key-value stores which provide a flexible, intuitive way to structure data, <strong><em>and</em></strong>, they provide very fast lookup time. Throughout the rest of these challenges, we will describe several common operations you can perform on objects so you can become comfortable applying these useful data structures in your programs.
In earlier challenges, we have both added to and modified an object's key-value pairs. Here we will see how we can <em>remove</em> a key-value pair from an object.
Let's revisit our <code>foods</code> object example one last time. If we wanted to remove the <code>apples</code> key, we can remove it by using the <code>delete</code> keyword like this:
# --description--
Now you know what objects are and their basic features and advantages. In short, they are key-value stores which provide a flexible, intuitive way to structure data, ***and***, they provide very fast lookup time. Throughout the rest of these challenges, we will describe several common operations you can perform on objects so you can become comfortable applying these useful data structures in your programs.
In earlier challenges, we have both added to and modified an object's key-value pairs. Here we will see how we can *remove* a key-value pair from an object.
Let's revisit our `foods` object example one last time. If we wanted to remove the `apples` key, we can remove it by using the `delete` keyword like this:
```js
delete foods.apples;
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
Use the delete keyword to remove the <code>oranges</code>, <code>plums</code>, and <code>strawberries</code> keys from the <code>foods</code> object.
</section>
Use the delete keyword to remove the `oranges`, `plums`, and `strawberries` keys from the `foods` object.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: 'The <code>foods</code> object should only have three keys: <code>apples</code>, <code>grapes</code>, and <code>bananas</code>.'
testString: 'assert(!foods.hasOwnProperty(''oranges'') && !foods.hasOwnProperty(''plums'') && !foods.hasOwnProperty(''strawberries'') && Object.keys(foods).length === 3);'
- text: The <code>oranges</code>, <code>plums</code>, and <code>strawberries</code> keys should be removed using <code>delete</code>.
testString: assert(code.search(/oranges:/) !== -1 && code.search(/plums:/) !== -1 && code.search(/strawberries:/) !== -1);
The `foods` object should only have three keys: `apples`, `grapes`, and `bananas`.
```js
assert(
!foods.hasOwnProperty('oranges') &&
!foods.hasOwnProperty('plums') &&
!foods.hasOwnProperty('strawberries') &&
Object.keys(foods).length === 3
);
```
</section>
The `oranges`, `plums`, and `strawberries` keys should be removed using `delete`.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(
code.search(/oranges:/) !== -1 &&
code.search(/plums:/) !== -1 &&
code.search(/strawberries:/) !== -1
);
```
<div id='js-seed'>
# --seed--
## --seed-contents--
```js
let foods = {
@@ -58,14 +65,7 @@ let foods = {
console.log(foods);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
let foods = {
@@ -83,5 +83,3 @@ delete foods.strawberries;
console.log(foods);
```
</section>