fix(guide): restructure curriculum guide articles (#36501)

* fix: restructure certifications guide articles
* fix: added 3 dashes line before prob expl
* fix: added 3 dashes line before hints
* fix: added 3 dashes line before solutions
This commit is contained in:
Randell Dawson
2019-07-24 00:59:27 -07:00
committed by mrugesh
parent c911e77eed
commit 1494a50123
990 changed files with 13202 additions and 8628 deletions

View File

@@ -1,11 +1,11 @@
---
title: Boo Who
---
![](//discourse-user-assets.s3.amazonaws.com/original/2X/3/3c8584a085a0deaea66b3400e6321eeadab552a2.jpg)
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
# Boo Who
### Problem Explanation:
---
## Problem Explanation
This program is very simple, the trick is to understand what a boolean primitive is. The programs requires a true or false answer.
@@ -13,50 +13,42 @@ This program is very simple, the trick is to understand what a boolean primitive
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean' target='_blank' rel='nofollow'>Boolean</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
* You will need to check for the type of the parameter to see if it is a boolean.
---
## Hints
> _try to solve the problem now_
### Hint 1
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
You will need to check for the type of the parameter to see if it is a boolean.
* To check for the type of a parameter, you can use `typeof`.
### Hint 2
To check for the type of a parameter, you can use `typeof`.
> _try to solve the problem now_
### Hint 3
Since you must return true or false you can use if statements or just have it return the boolean used for the if statement.
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
* Since you must return true or false you can use if statements or just have it return the boolean used for the if statement.
> _try to solve the problem now_
---
## Solutions
## Spoiler Alert!
<details><summary>Solution 1 (Click to Show/Hide)</summary>
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
```javascript
function booWho(bool) {
return typeof bool === 'boolean';
}
function booWho(bool) {
return typeof bool === "boolean";
}
// test here
booWho(null);
// test here
booWho(null);
```
# Code Explanation:
#### Code Explanation
Uses the operator `typeof` to check if the variable is a boolean. If it is, it will return `true`. Otherwise, if it is any other type it will return `false`.
* Uses the operator `typeof` to check if the variable is a boolean. If it is, it will return `true`. Otherwise, if it is any other type it will return `false`.
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof' target='_blank' rel='nofollow'>typeof</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,11 +1,11 @@
---
title: Chunky Monkey
---
![](//discourse-user-assets.s3.amazonaws.com/original/2X/a/aadd6bead83ab7d79a795c326f005a89e6ad81f5.png)
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
# Chunky Monkey
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
---
## Problem Explanation
Our goal for this Algorithm is to split `arr` (first argument) into smaller chunks of arrays with the length provided by `size` (second argument). There are 4 green checks (objectives) our code needs to pass in order to complete this Algorithm:
@@ -19,56 +19,52 @@ Our goal for this Algorithm is to split `arr` (first argument) into smaller chun
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push' rel='nofollow'>Array.push()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice' target='_blank' rel='nofollow'>Array.slice()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
The links above suggest to use `Array.push()`, so let's start by first creating a new array to store the smaller arrays we will soon have like this:
```javascript
var newArray = [];
```
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:")</a> Hint: 2
```javascript
var newArray = [];
```
### Hint 2
Next we'll need a `for loop` to loop through `arr`.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
Finally, we need a method to do the actual splitting and we can use `Array.slice()` to do that. The key to this Algorithm is understanding how a `for loop`, `size`, `Array.slice()` and `Array.push()` all work together.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
```javascript
function chunkArrayInGroups(arr, size) {
function chunkArrayInGroups(arr, size) {
var temp = [];
var result = [];
var temp = [];
var result = [];
for (var a = 0; a < arr.length; a++) {
if (a % size !== size - 1)
temp.push(arr[a]);
else {
temp.push(arr[a]);
result.push(temp);
temp = [];
}
}
if (temp.length !== 0)
result.push(temp);
return result;
for (var a = 0; a < arr.length; a++) {
if (a % size !== size - 1) temp.push(arr[a]);
else {
temp.push(arr[a]);
result.push(temp);
temp = [];
}
}
if (temp.length !== 0) result.push(temp);
return result;
}
```
### Code Explanation:
#### Code Explanation
* Firstly, we create two empty arrays called `temp` and `result`, which we will eventually return.
* Our **for loop** loops until `a` is equal to or more than the length of the array in our test.
@@ -82,19 +78,22 @@ Finally, we need a method to do the actual splitting and we can use `Array.slice
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push' rel='nofollow'>Array.push()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for' target='_blank' rel='nofollow'>For Loops</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```javascript
function chunkArrayInGroups(arr, size) {
// Break it up.
var arr2 = [];
for (var i = 0; i < arr.length; i+=size) {
arr2.push(arr.slice(i , i+size));
}
return arr2;
}
function chunkArrayInGroups(arr, size) {
// Break it up.
var arr2 = [];
for (var i = 0; i < arr.length; i += size) {
arr2.push(arr.slice(i, i + size));
}
return arr2;
}
```
### Code Explanation:
#### Code Explanation
* First, we create an empty array `arr2` where we will store our 'chunks'.
* The for loop starts at zero, increments by `size` each time through the loop, and stops when it reaches `arr.length`.
@@ -108,23 +107,26 @@ Finally, we need a method to do the actual splitting and we can use `Array.slice
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice' target='_blank' rel='nofollow'>Array.slice()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for' target='_blank' rel='nofollow'>For Loops</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
```javascript
function chunkArrayInGroups(arr, size) {
// Break it up.
var newArr = [];
var i = 0;
</details>
while (i < arr.length) {
newArr.push(arr.slice(i, i+size));
i += size;
}
return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
<details><summary>Solution 3 (Click to Show/Hide)</summary>
```javascript
function chunkArrayInGroups(arr, size) {
// Break it up.
var newArr = [];
var i = 0;
while (i < arr.length) {
newArr.push(arr.slice(i, i + size));
i += size;
}
return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
```
### Code Explanation:
#### Code Explanation
* Firstly, we create two variables. `newArr` is an empty array which we will push to. We also have the `i` variable set to zero, for use in our while loop.
* Our while loop loops until `i` is equal to or more than the length of the array in our test.
@@ -141,18 +143,21 @@ Finally, we need a method to do the actual splitting and we can use `Array.slice
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice' target='_blank' rel='nofollow'>Array.slice()</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/while' target='_blank' rel='nofollow'>While Loops</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution 2:
</details>
<details><summary>Solution 4 (Click to Show/Hide)</summary>
```javascript
function chunkArrayInGroups(arr, size) {
var newArr = [];
while (arr.length) {
newArr.push(arr.splice(0,size));
}
return newArr;
}
function chunkArrayInGroups(arr, size) {
var newArr = [];
while (arr.length) {
newArr.push(arr.splice(0, size));
}
return newArr;
}
```
### Code Explanation:
#### Code Explanation
* Firstly, we create a variable. `newArr` is an empty array which we will push to.
* Our `while` loop loops until the length of the array in our test is not 0.
@@ -166,19 +171,23 @@ Finally, we need a method to do the actual splitting and we can use `Array.slice
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice' target='_blank' rel='nofollow'>Array.splice()</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/while' target='_blank' rel='nofollow'>While Loops</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution 3:
</details>
<details><summary>Solution 5 (Click to Show/Hide)</summary>
```javascript
function chunkArrayInGroups(arr, size) {
if (arr.length <= size){
return [arr];
}
else {
return [arr.slice(0,size)].concat(chunkArrayInGroups(arr.slice(size),size));
}
}
function chunkArrayInGroups(arr, size) {
if (arr.length <= size) {
return [arr];
} else {
return [arr.slice(0, size)].concat(
chunkArrayInGroups(arr.slice(size), size)
);
}
}
```
### Code Explanation:
#### Code Explanation
* Array smaller than size is returned nested.
* For any array larger than size, it is split in two. First segment is nested and concatenated with second segment which makes a recursive call.
@@ -187,9 +196,4 @@ Finally, we need a method to do the actual splitting and we can use `Array.slice
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Recursion' target='_blank' rel='nofollow'>Recursion</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice' target='_blank' rel='nofollow'>Array.slice()</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,26 +1,27 @@
---
title: Confirm the Ending
---
## Confirm the Ending
# Confirm the Ending
---
## Solutions
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
# 🌻 Intermediate Code Solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
(Declarative approach)
```javascript
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
return str.slice(str.length - target.length) === target;
}
confirmEnding("He has to give me a new name", "name");
```
# Code Explanation:
#### Code Explanation
- First we use the `slice` method copy the string.
- In order to get the last characters in `str` equivalent to the `target`'s length we use the `slice` method.
- The first parameter inside the `slice` method is the starting index and the second parameter would be the ending index.
@@ -29,33 +30,34 @@ confirmEnding("He has to give me a new name", "name");
- We substract the length of `str` and the length of `target`, that way, we shall get the last remaining characters equivalent to the `target`'s length.
- Finally we compare the return result of slice to `target` and check if they have the same characters.
### Relevant Links
#### Relevant Links
- [String.prototype.slice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice)
</details>
# ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:")Advanced Code Solution:
<details><summary>Solution 2 (Click to Show/Hide)</summary>
(using Regular Expression)
```javascript
```javascript
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
let re = new RegExp(target+'$','i');
let re = new RegExp(target + "$", "i");
return re.test(str);
}
console.log(confirmEnding("Bastian", "n"));
```
## Code Explanation:
#### Code Explanation
- We need to make a pattern from the `target` variable that exists at the end of the string `str`.
- Since we will use a variable that will change the pattern each time the function is called, we will use the constructor of the regular expression object `new RegExp(pattern[, flags])`, so we start with: `new RegExp(target)`.
- Then we have to check at the end of the string, so we concatenate to the `target` variable the `$` character to match the end: `new RegExp(target+'$')`.
- We use the flag `i` to ignore the case of the pattern and we have our completed RegExp: `new RegExp(target+'$','i')`, or we can ommit the flag entirely.
- Finally, we are using our regular expression with the `test` method to the given string, to check if the string ends with the pattern and return true or false accordingly.
### Relevant Links
#### Relevant Links
- [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
- [RegExp.prototype.test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test)
</details>

View File

@@ -1,9 +1,11 @@
---
title: Convert Celsius to Fahrenheit
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Convert Celsius to Fahrenheit
---
## Problem Explanation
The algorithm to convert from Celsius to Fahrenheit is the temperature in Celsius times `9/5`, plus `32`.
@@ -14,48 +16,43 @@ You are given a variable **celsius** representing a temperature in Celsius. Use
* <a href='http://www.purplemath.com/modules/orderops.htm' target='_blank' rel='nofollow'>The Order of Operations: PEMDAS</a>
* <a href='https://www.khanacademy.org/math/pre-algebra/order-of-operations/order_of_operations/v/order-of-operations' target='_blank' rel='nofollow'>Order of Operation: Video</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
Take a look at the code. There is an area that you're not supposed to edit. From there, ask yourself - what is used there that I haven't seen before?
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
Keep in mind the **order of operation** check the link in the _links_ section for more information.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
```javascript
function convertToF(celsius) {
// Only change code below this line
var fahrenheit = (celsius * (9/5)) + 32;
function convertToF(celsius) {
// Only change code below this line
var fahrenheit = celsius * (9 / 5) + 32;
// Only change code above this line
if ( typeof fahrenheit !== 'undefined' ) {
return fahrenheit;
} else {
return 'fahrenheit not defined';
}
}
// Only change code above this line
if (typeof fahrenheit !== "undefined") {
return fahrenheit;
} else {
return "fahrenheit not defined";
}
}
// Change the inputs below to test your code
convertToF(30);
// Change the inputs below to test your code
convertToF(30);
```
### Code Explanation:
#### Code Explanation
* Declare the **fahrenheit** variable.
* Make sure the proper order of arithmetic operations is followed by using parenthesis (`()`) when needed.
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,20 +1,19 @@
---
title: Factorialize a Number
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
## Hints for Solution
# Factorialize a Number
### ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint:
---
## Hints
### Hint 1
You know your solution should return `1` when the number passed to the function is `0` or `1`. Also, the final value returned will be the product of all the numbers between 1 and the number (inclusive). If you initialize the value for the product to `1`, then think how you could start at the given number and continue decrementing this number until a specific value while multiplying the product by the number at each step.
> _try to solve the problem now_
## Hints for a Recursive Solution
### ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
**Recursive Solution**
This one starts easily since `0! = 1`, so you can go ahead and simply `return 1` there.
@@ -22,23 +21,17 @@ We can use that as an `if` in order to break the loop we're going to create usin
This is also why **instead** of having _"finished"_, a function is always said to _"have returned"_. And now this...
> _try to solve the problem now_
### ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
**Understanding recursion**
Recursion refers to a function repeating (calling) itself. In this case we are basically returning the given number (i.e. 5), multiplied by the function itself but this time the value passed to the _num_ parameter is `num-1` (which initially translates to 4). The very function is going to **run inside itself** interesting, eh?
> _try to solve the problem now_
### ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
**Understanding the flow**
The first **returned** value can be visualized better if you think about those parenthesis operations you did in secondary school where you do the math inside every parenthesis from inside out, bracket and square bracket until you get a final result (a total). This time it's the same thing, look at the program flow:
#### During the first execution of the function:
**During the first execution of the function:**
[**num** = 5]
@@ -50,7 +43,7 @@ Is 5 _equal_ to 1 or 0? **No** ---> Oki doki, let's continue...
What it returns can be viewed as `(5*(4*(3*(2*1))))` or just `5 * 4 * 3 * 2 * 1`, and the function will return the result of that operation: `120`. Now, let's check what the rest of the executions do:
#### During the rest of the executions:
**During the rest of the executions**:
**Second Execution**: _num_ = 5-1 = **4** -> is _num_ 0 or 1? No
@@ -68,24 +61,17 @@ What it returns can be viewed as `(5*(4*(3*(2*1))))` or just `5 * 4 * 3 * 2 * 1`
--> return **1**. And this is where the recursion stops because there are no more executions.
Got it? ![:wink:](https://forum.freecodecamp.com/images/emoji/emoji_one/wink.png?v=3 ":wink:")
> _try to solve the problem now_
### Relevant Links
#### Relevant Links
* <a href='https://www.youtube.com/watch?v=R8SjM4DKK80' target='_blank' rel='nofollow'>JS Functions</a>
* <a href='https://www.youtube.com/watch?v=k7-N8R0-KY4' target='_blank' rel='nofollow'>Recursion in JS</a>
## Spoiler Alert!
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
---
## Solutions
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution #1:
<details><summary>Click to see solution</summary>
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function factorialize(num) {
@@ -98,39 +84,39 @@ function factorialize(num) {
factorialize(5);
```
#### Code Explanation:
#### Code Explanation
- Since the return values for the function will always be greater than or equal to 1, `product` is initialized at one. For the case where the number is `0`, the for loop condition will be false, but since `product` is initialized as `1`, it will have the correct value when the `return` statement is executed.
- For all numbers passed to the function which are greater than one, the simple `for` loop will decrement `num` by one each iteration and recalculate `product` down to the value `1`.
</details><br>
</details>
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution #2 (using Recursion):
<details><summary>Click to see solution</summary>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
(using Recursion)
```js
function factorialize(num) {
if (num === 0) { return 1; }
return num * factorialize(num-1);
if (num === 0) {
return 1;
}
return num * factorialize(num - 1);
}
factorialize(5);
```
#### Code Explanation:
#### Code Explanation
Notice at the first line we have the terminal condition, i.e a condition to check the end of the recursion. If `num == 0`, then we return 1, i.e. effectively ending the recursion and informing the stack to propagate this value to the upper levels. If we do not have this condition, the recursion would go on until the stack space gets consumed, thereby resulting in a <a href='https://en.wikipedia.org/wiki/Stack_overflow' target='_blank' rel='nofollow'>Stack Overflow</a>.
### Relevant Links
#### Relevant Links
* <a href='https://www.codecademy.com/en/courses/javascript-lesson-205/0/1' target='_blank' rel='nofollow'>Recursion</a>
* <a href='https://en.wikipedia.org/wiki/Factorial' target='_blank' rel='nofollow'>Factorialization</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators' target='_blank' rel='nofollow'>Arithmetic Operators</a>
</details><br>
</details>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
<details><summary>Click to see solution</summary>
<details><summary>Solution 3 (Click to Show/Hide)</summary>
```js
function factorialize(num, factorial = 1) {
@@ -144,23 +130,17 @@ function factorialize(num, factorial = 1) {
factorialize(5);
```
#### Code Explanation:
#### Code Explanation
In this solution, we use <a href='https://stackoverflow.com/questions/33923/what-is-tail-recursion' target='_blank' rel='nofollow'>Tail Recursion</a> to optimize the the memory use.
* In this solution, we use <a href='https://stackoverflow.com/questions/33923/what-is-tail-recursion' target='_blank' rel='nofollow'>Tail Recursion</a> to optimize the the memory use.
In traditional head recursion, the typical model is that you perform your recursive calls first, and then you take the return value of the recursive call and calculate the result. In this manner, you don't get the result of your calculation until you have returned from every recursive call.
* In traditional head recursion, the typical model is that you perform your recursive calls first, and then you take the return value of the recursive call and calculate the result. In this manner, you don't get the result of your calculation until you have returned from every recursive call.
In tail recursion, you perform your calculations first, and then you execute the recursive call, passing the results of your current step to the next recursive step. This results in the last statement being in the form of (return (recursive-function params)).
* In tail recursion, you perform your calculations first, and then you execute the recursive call, passing the results of your current step to the next recursive step. This results in the last statement being in the form of (return (recursive-function params)).
In this solution, with each evaluation of the recursive call, the factorial is updated. This is different from the head-recursive solution where all evaluation calculations are stored on the stack until the base case is reached.
* In this solution, with each evaluation of the recursive call, the factorial is updated. This is different from the head-recursive solution where all evaluation calculations are stored on the stack until the base case is reached.
### Relevant Links
#### Relevant Links
* <a href='https://www.geeksforgeeks.org/tail-recursion/' target='_blank' rel='nofollow'>Tail Recursion</a>
</details><br>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,11 +1,11 @@
---
title: Falsy Bouncer
---
![](//discourse-user-assets.s3.amazonaws.com/original/2X/5/55dedad40d9f3f662c70d1eac4effc00c7d26bd9.jpg)
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
# Falsy Bouncer
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
---
## Problem Explanation
Remove all <a href='https://guide.freecodecamp.org/javascript/falsy-values/' target='_blank' rel='nofollow'>falsy</a> values from an array.
@@ -13,49 +13,44 @@ Remove all <a href='https://guide.freecodecamp.org/javascript/falsy-values/' tar
* <a href='https://guide.freecodecamp.org/javascript/falsy-values/' target='_blank' rel='nofollow'>Falsy Values</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
Falsy is something which evaluates to FALSE. There are only six falsy values in JavaScript: undefined, null, NaN, 0, "" (empty string), and false of course.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
We need to make sure we have all the falsy values to compare, we can know it, maybe with a function with all the falsy values...
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
Then we need to add a `filter()` with the falsy values function...
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function bouncer(arr) {
let newArray = [];
for (var i = 0; i < arr.length; i++){
if (arr[i])
newArray.push(arr[i]);
for (var i = 0; i < arr.length; i++) {
if (arr[i]) newArray.push(arr[i]);
}
return newArray;
}
```
### Code Explanation:
We create a new empty array.
We use a for cycle to iterate over all elements of the provided array (arr).
We use the if statement to check if the current element is <a href='http://forum.freecodecamp.com/t/javascript-truthy-value/15975' target='_blank' rel='nofollow'>truthy</a> or <a href='https://guide.freecodecamp.org/javascript/falsy-values/' target='_blank' rel='nofollow'>falsy</a>.
If the element is truthy, we push it to the new array (newArray). This result in the new array (newArray) containing only truthy elements.
We return the new array (newArray).
#### Code Explanation
* We create a new empty array.
* We use a for cycle to iterate over all elements of the provided array (arr).
* We use the if statement to check if the current element is <a href='http://forum.freecodecamp.com/t/javascript-truthy-value/15975' target='_blank' rel='nofollow'>truthy</a> or <a href='https://guide.freecodecamp.org/javascript/falsy-values/' target='_blank' rel='nofollow'>falsy</a>.
* If the element is truthy, we push it to the new array (newArray). This result in the new array (newArray) containing only truthy elements.
* We return the new array (newArray).
#### Relevant Links
@@ -64,30 +59,23 @@ We return the new array (newArray).
* [Falsey values](https://www.freecodecamp.org/forum/t/javascript-falsy-values/14664)
* [Array.prototype.push](https://www.freecodecamp.org/forum/t/javascript-array-prototype-push/14298)
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```js
function bouncer(arr) {
return arr.filter(Boolean);
}
function bouncer(arr) {
return arr.filter(Boolean);
}
```
### Code Explanation:
#### Code Explanation
The `Array.prototype.filter` method expects a function that returns a `Boolean` value which takes a single argument and returns `true` for <a href='http://forum.freecodecamp.com/t/javascript-truthy-value/15975' target='_blank' rel='nofollow'>truthy</a> value or `false` for <a href='https://guide.freecodecamp.org/javascript/falsy-values/' target='_blank' rel='nofollow'>falsy</a> value. Hence we pass the built-in `Boolean` function.
* The `Array.prototype.filter` method expects a function that returns a `Boolean` value which takes a single argument and returns `true` for <a href='http://forum.freecodecamp.com/t/javascript-truthy-value/15975' target='_blank' rel='nofollow'>truthy</a> value or `false` for <a href='https://guide.freecodecamp.org/javascript/falsy-values/' target='_blank' rel='nofollow'>falsy</a> value. Hence we pass the built-in `Boolean` function.
#### Relevant Links
* <a href='http://forum.freecodecamp.com/t/javascript-boolean/14311' target='_blank' rel='nofollow'>Boolean</a>
* <a href='http://forum.freecodecamp.com/t/javascript-truthy-value/15975' target='_blank' rel='nofollow'>Truthy</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-filter/14289' target='_blank' rel='nofollow'>Array.prototype.filter()</a>
## ![:trophy:](https://forum.freecodecamp.com/images/emoji/emoji_one/trophy.png?v=3 ":trophy:") Credits:
If you found this page useful, you can give thanks by copying and pasting this on the main chat:
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,9 +1,11 @@
---
title: Find the Longest Word in a String
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Find the Longest Word in a String
---
## Problem Explanation
You have to go through each word and figure out which one is the longest and return not the word, but how many characters it has.
@@ -11,31 +13,29 @@ You have to go through each word and figure out which one is the longest and ret
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length' target='_blank' rel='nofollow'>JS String Length</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
You should split the string into an array of words.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
You will need to figure out a way to keep track globally of the greatest current length.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
Remember how to get the length of elements on the array? `Array[index].length`.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
function findLongestWordLength(str) {
var words = str.split(' ');
@@ -51,7 +51,7 @@ Remember how to get the length of elements on the array? `Array[index].length`.
}
### Code Explanation:
#### Code Explanation
Take the string and convert it into an array of words. Declare a variable to keep track of the maximum length and loop from 0 to the length of the array of words.
@@ -61,7 +61,7 @@ Then check for the longest word by comparing the current word to the previous on
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/length' target='_blank' rel='nofollow'>JS Array.length</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
<details><summary>Solution 2 (Click to Show/Hide)</summary>
**Using `.reduce()`**
@@ -73,7 +73,7 @@ Then check for the longest word by comparing the current word to the previous on
}
### Code Explanation:
#### Code Explanation
For more information on `reduce` <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce' target='_blank' rel='nofollow'>click here.</a>
@@ -85,17 +85,19 @@ In case you're wondering about that `0` after the callback function, it is used
* <a href='http://forum.freecodecamp.com/t/using-array-prototype-reduce-to-reduce-conceptual-boilerplate-for-problems-on-arrays/14687' target='_blank' rel='nofollow'>JS Reduce Made Easy</a>
* <a href='http://forum.freecodecamp.com/t/javascript-math-max/14682.md' target='_blank' rel='nofollow'>JS Math Max</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution 2:
</details>
<details><summary>Solution 3 (Click to Show/Hide)</summary>
**Using `.map()`**
```javascript
function findLongestWordLength(str) {
return Math.max(...str.split(" ").map(word => word.length));
return Math.max(...str.split(" ").map(word => word.length));
}
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLjU/6' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
#### Code Explanation
We provide `Math.max` with the length of each word as argument, and it will simply return the highest of all.
@@ -110,40 +112,41 @@ Then, we will make another array, made from the lengths of each element of the `
Finally, we pass the array as argument for the Math.max function with the spread operator `...`
For more information on `map` <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map' target='_blank' rel='nofollow'>click here.</a>
</details>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
<details><summary>Solution 4 (Click to Show/Hide)</summary>
**Using recursiveness**
**Using recursion**
function findLongestWordLength(str) {
```js
function findLongestWordLength(str) {
//split the string into individual words
//(important!!, you'll see why later)
str = str.split(" ");
//split the string into individual words
//(important!!, you'll see why later)
str = str.split(" ");
//str only has 1 element left that is the longest element,
//return the length of that element
if (str.length == 1) {
return str[0].length;
}
//str only has 1 element left that is the longest element,
//return the length of that element
if(str.length == 1){
return str[0].length;
}
//if the first element's length is greater than the second element's (or equal)
//remove the second element and recursively call the function)
if (str[0].length >= str[1].length) {
str.splice(1, 1);
return findLongestWordLength(str.join(" "));
}
//if the first element's length is greater than the second element's (or equal)
//remove the second element and recursively call the function)
if(str[0].length >= str[1].length){
str.splice(1,1);
return findLongestWordLength(str.join(" "));
}
//if the second element's length is greater thant the first element's start
//call the function past the first element
if (str[0].length <= str[1].length) {
// from the first element to the last element inclusive.
return findLongestWordLength(str.slice(1, str.length).join(" "));
}
}
```
//if the second element's length is greater thant the first element's start
//call the function past the first element
if(str[0].length <= str[1].length){
// from the first element to the last element inclusive.
return findLongestWordLength(str.slice(1,str.length).join(" "));
}
}
### Code Explanation:
#### Code Explanation
The first line splits the string into individual words. Then we check if `str` only has 1 element left then that is the longest element and we return it. If the first element's length is greater than the second element's (or equal), we remove the second element and recursively call the function `findLongestWord`. However, if the second element's length is greater thant the first element's start, then we call the function past the first element.
@@ -152,8 +155,4 @@ The first line splits the string into individual words. Then we check if `str` o
* <a href='https://www.youtube.com/watch?v=R8SjM4DKK80' target='_blank' rel='nofollow'>JS Functions</a>
* <a href='https://www.youtube.com/watch?v=k7-N8R0-KY4' target='_blank' rel='nofollow'>Recursion Basics</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,52 +1,59 @@
---
title: Finders Keepers
---
![](//discourse-user-assets.s3.amazonaws.com/original/2X/f/ff2fd8ffa014eea28587a8ef4933340d3dcc4b09.jpg)
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
## ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Finders Keepers
---
## Problem Explanation
We need to return the element from an array that passes a function. Both the `function` and the `array` are passed into our function `findElement(arr, func)`.
## Hint: 1
Looking through the array can be done with a `for` loop.
>*try to solve the problem now*
## Hint: 2
---
## Hints
### Hint 1
We need to return the element from an array that passes a function. Both the `function` and the `array` are passed into our function `findElement(arr, func)`. Looking through the array can be done with a `for` loop.
### Hint 2
`num` is passed to the function. We will need to set it to the elements we want to check with the function.
>*try to solve the problem now*
## Hint: 3
### Hint 3
Do not forget, if none of the numbers in the array pass the test, it should return `undefined`.
>*try to solve the problem now*
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```javascript
function findElement(arr, func) {
let num = 0;
for(var i = 0; i < arr.length; i++) {
for (var i = 0; i < arr.length; i++) {
num = arr[i];
if (func(num)) {
return num;
}
}
return undefined;
}
```
## Code Explanation
#### Code Explanation
* Challenge asks us to look through array. This is done using a `for` loop.
* The `num` variable is being passed into the function, so we set it to each index in our array.
* The pre-defined function already checks each number for us, so if it is "true", we return that num.
* If none of the numbers in the array pass the function's test, we return undefined.
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```javascript
function findElement(arr, func) {
return arr.find(func);
@@ -57,23 +64,21 @@ function findElement(arr, func) {
* [Array.prototype.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
<details><summary>Solution 3 (Click to Show/Hide)</summary>
```javascript
function findElement(arr, func) {
return arr[(arr.map(func)).indexOf(true)];
return arr[arr.map(func).indexOf(true)];
}
```
## Code Explanation
#### Code Explanation
1. Look through the array given in the 1st paramater "arr" using the .map() method
2. Use the function in the 2nd parameter as the callback function in arr.map()
3. Acquire the index of the first number that meets the condition in the function.
4. Use that index to display the first available number that meets the condition.
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories -- **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,13 +1,11 @@
---
title: Basic Algorithm Scripting
---
## Basic Algorithm Scripting
# Basic Algorithm Scripting
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@@ -1,9 +1,11 @@
---
title: Mutations
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Mutations
---
## Problem Explanation
* Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array..
@@ -11,46 +13,44 @@ title: Mutations
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-indexof/15936' target='_blank' rel='nofollow'>String.indexOf()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
* If everything is lowercase it will be easier to compare.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
* Our strings might be easier to work with if they were arrays of characters.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
* A loop might help. Use `indexOf()` to check if the letter of the second word is on the first.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Procedural**
function mutation(arr) {
var test = arr[1].toLowerCase();
var target = arr[0].toLowerCase();
for (var i=0;i<test.length;i++) {
if (target.indexOf(test[i]) < 0)
return false;
}
return true;
}
```js
function mutation(arr) {
var test = arr[1].toLowerCase();
var target = arr[0].toLowerCase();
for (var i = 0; i < test.length; i++) {
if (target.indexOf(test[i]) < 0) return false;
}
return true;
}
```
### Code Explanation:
#### Code Explanation
First we make the two strings in the array lowercase. `test` will hold what we are looking for in `target`.
Then we loop through our test characters and if any of them is not found we `return false`.
@@ -62,21 +62,24 @@ If they are _all_ found, the loop will finish without returning anything and we
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-tolowercase/15948' target='_blank' rel='nofollow'>String.toLowerCase()</a>
* <a href='http://forum.freecodecamp.com/t/javascript-for-loop/14666s-Explained' target='_blank' rel='nofollow'>For loops</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
**Declarative**
function mutation(arr) {
return arr[1].toLowerCase()
.split('')
.every(function(letter) {
return arr[0].toLowerCase()
.indexOf(letter) != -1;
});
}
```js
function mutation(arr) {
return arr[1]
.toLowerCase()
.split("")
.every(function(letter) {
return arr[0].toLowerCase().indexOf(letter) != -1;
});
}
```
### Code Explanation:
#### Code Explanation
Grab the second string, lowercase and turn it into an array; then make sure _every_ one of its _letters_ is a part of the lowercased first string.
@@ -87,8 +90,4 @@ Grab the second string, lowercase and turn it into an array; then make sure _eve
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-split/15944' target='_blank' rel='nofollow'>Array.split()</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-every/14287' target='_blank' rel='nofollow'>Array.every()</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,9 +1,11 @@
---
title: Repeat a String Repeat a String
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Repeat a String Repeat a String
---
## Problem Explanation
The program is very simple, we have to take a variable and return that variable being repeated certain amount of times. No need to add space or anything, just keep repeating it into one single string.
@@ -11,45 +13,47 @@ The program is very simple, we have to take a variable and return that variable
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String' target='_blank' rel='nofollow'>Global String Object</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
The program is very simple, we have to take a variable and return that variable being repeated certain amount of times. No need to add space or anything, just keep repeating it into one single string.
### Hint 2
You can't edit strings, you will need to create a variable to store the new string.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 3
Create a loop to repeat the code as many times as needed.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 4
Make the variable created store the current value and append the word to it.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Solution ahead!**
```js
function repeatStringNumTimes(str, num) {
var accumulatedStr = "";
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
while (num > 0) {
accumulatedStr += str;
num--;
}
function repeatStringNumTimes(str, num) {
var accumulatedStr = '';
return accumulatedStr;
}
```
while (num > 0) {
accumulatedStr += str;
num--;
}
return accumulatedStr;
}
### Code Explanation:
#### Code Explanation
* Create an empty string variable to store the repeated word.
* Use a while loop or for loop to repeat code as many times as needed according to `num`
@@ -60,21 +64,23 @@ Make the variable created store the current value and append the word to it.
* <a>JS while Loop</a>
* <a href='https://forum.freecodecamp.com/t/javascript-for-loop/14666s-Explained' target='_blank' rel='nofollow'>JS For Loops Explained</a>
</details>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
<details><summary>Solution 2 (Click to Show/Hide)</summary>
function repeatStringNumTimes(str, num) {
if (num < 1) {
return "";
} else if (num === 1) {
return str;
} else {
return str + repeatStringNumTimes(str, num - 1);
}
}
```js
function repeatStringNumTimes(str, num) {
if (num < 1) {
return "";
} else if (num === 1) {
return str;
} else {
return str + repeatStringNumTimes(str, num - 1);
}
}
```
### Code Explanation:
#### Code Explanation
* This solution uses recursion.
* We check if `num` is negative and return an empty string if true.
@@ -85,16 +91,19 @@ Make the variable created store the current value and append the word to it.
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Recursion' target='_blank' rel='nofollow'>Functions - Recursion</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
function repeatStringNumTimes(str, num) {
return num > 0 ? str.repeat(num) : '';
}
<details><summary>Solution 3 (Click to Show/Hide)</summary>
repeatStringNumTimes("abc", 3);
```js
function repeatStringNumTimes(str, num) {
return num > 0 ? str.repeat(num) : "";
}
repeatStringNumTimes("abc", 3);
```
### Code Explanation:
#### Code Explanation
* This solution takes a declarative approach.
* It is similar to the third solution, except it uses the ternary operator form of the `if` statement.
@@ -102,9 +111,4 @@ Make the variable created store the current value and append the word to it.
#### Relevant Links
* <a href='https://forum.freecodecamp.com/t/javascript-ternary-operator/15973' target='_blank' rel='nofollow'>JS Ternary</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,59 +1,57 @@
---
title: Return Largest Numbers in Arrays
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Return Largest Numbers in Arrays
---
## Problem Explanation
You will get an array that contains sub arrays of numbers and you need to return an array with the largest number from each of the sub arrays.
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
You will need to keep track of the array with the answer and the largest number of each sub-array.
---
## Hints
> _try to solve the problem now_
### Hint 1
You will get an array that contains sub arrays of numbers and you need to return an array with the largest number from each of the sub arrays. You will need to keep track of the array with the answer and the largest number of each sub-array.
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
You can work with multidimensional arrays by `Array[Index][SubIndex]`
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
Pay close attention to the timing of the storing of variables when working with loops
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solutions ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**(Procedural approach)**
function largestOfFour(arr) {
var results = [];
for (var n = 0; n < arr.length; n++) {
var largestNumber = arr[n][0];
for (var sb = 1; sb < arr[n].length; sb++) {
if (arr[n][sb] > largestNumber) {
largestNumber = arr[n][sb];
}
}
results[n] = largestNumber;
```js
function largestOfFour(arr) {
var results = [];
for (var n = 0; n < arr.length; n++) {
var largestNumber = arr[n][0];
for (var sb = 1; sb < arr[n].length; sb++) {
if (arr[n][sb] > largestNumber) {
largestNumber = arr[n][sb];
}
return results;
}
results[n] = largestNumber;
}
### Code Explanation:
return results;
}
```
#### Code Explanation
* Create a variable to store the _results_ as an array.
* Create an outer loop to iterate through the outer array.
@@ -67,20 +65,23 @@ Pay close attention to the timing of the storing of variables when working with
* <a href='http://forum.freecodecamp.com/t/javascript-for-loop/14666s-Explained' target='_blank' rel='nofollow'>For loops</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
**(Declarative approach)**
function largestOfFour(arr) {
return arr.map(function(group){
return group.reduce(function(prev, current) {
return (current > prev) ? current : prev;
});
});
}
```js
function largestOfFour(arr) {
return arr.map(function(group) {
return group.reduce(function(prev, current) {
return current > prev ? current : prev;
});
});
}
```
### Code Explanation:
#### Code Explanation
* we map all items within the main array to a new array using `Array.prototype.map()` and return this array as the final result
* within each inner array, we reduce its contents down to a single value using `Array.prototype.reduce()`
@@ -93,18 +94,21 @@ Pay close attention to the timing of the storing of variables when working with
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-reduce/14299' target='_blank' rel='nofollow'>Array.prototype.reduce()</a>
* <a href='http://forum.freecodecamp.com/t/javascript-ternary-operator/15973' target='_blank' rel='nofollow'>Ternary Operators</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
<details><summary>Solution 3 (Click to Show/Hide)</summary>
**(Declarative approach)**
function largestOfFour(arr) {
return arr.map(Function.apply.bind(Math.max, null));
}
```js
function largestOfFour(arr) {
return arr.map(Function.apply.bind(Math.max, null));
}
```
#### Code Explanation
### Code Explanation:
TL;DR: We build a special callback function (using the `Function.bind` method), that works just like `Math.max` but also has `Function.prototype.apply`'s ability to take arrays as its arguments ![:smiley:](https://forum.freecodecamp.com/images/emoji/emoji_one/smiley.png?v=3 ":smiley:")
TL;DR: We build a special callback function (using the `Function.bind` method), that works just like `Math.max` but also has `Function.prototype.apply`'s ability to take arrays as its arguments.
* We start by mapping through the elements inside the main array. Meaning each one of the inner arrays.
* Now the need a callback function to find the max of each inner array provided by the map.
@@ -137,9 +141,4 @@ Here we're passing `null` as the _context_ of the `Function.prototype.apply` met
* <a href ='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max' target='_blank' rel='nofollow'> Math.max</a>
* <a href='http://devdocs.io/#q=js+Function+apply' target='_blank' rel='nofollow'>Function.prototype.apply on DevDocs</a>
* <a href='http://devdocs.io/#q=js+Function+bind' target='_blank' rel='nofollow'>Function.bind on DevDocs</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,44 +1,54 @@
---
title: Reverse a String
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
# Reverse a String
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
We need to take the string and reverse it, so if it originally reads 'hello', it will now read 'olleh'. We will need to split the string, and therefore we will be working with Arrays as well.
### Hint 2
Start by splitting the string by characters.
> _try to solve the problem now_
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split' target='_blank' rel='nofollow'>str.split()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 3
Look up the built in function to reverse a string.
> _try to solve the problem now_
#### Relevant Links
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse' target='_blank' rel='nofollow'>arr.reverse()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 4
Do not forget to join the characters back together after you reverse them.
> _try to solve the problem now_
#### Relevant Links
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join' target='_blank' rel='nofollow'>arr.join()</a>
## Spoiler Alert!
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
---
## Solutions
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution #1:
<details><summary>Click to see solution</summary>
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function reverseString(str) {
return str.split('').reverse().join('');
return str
.split("")
.reverse()
.join("");
}
```
#### Code Explanation:
#### Code Explanation
* Our goal is to take the input, `str`, and return it in reverse. Our first step is to split the string by characters using `split('')`. Notice that we don't leave anything in between the single quotes, this tells the function to split the string by each character.
@@ -48,28 +58,26 @@ function reverseString(str) {
* Finally, we _chain_ `join('')` to put our characters back together into a string. Notice once again that we left no spaces in the argument for join, this makes sure that the array of characters is joined back together by each character.
### Relevant Links
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split' target='_blank' rel='nofollow'>str.split()</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse' target='_blank' rel='nofollow'>arr.reverse()</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join' target='_blank' rel='nofollow'>arr.join()</a>
</details><br>
</details>
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution #2:
<details><summary>Click to see solution</summary>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```js
function reverseString(str) {
for (var reversedStr = '', i = str.length - 1; i >= 0; i--){
for (var reversedStr = "", i = str.length - 1; i >= 0; i--) {
reversedStr += str[i];
}
return reversedStr;
};
}
```
#### Code Explanation:
#### Code Explanation
* Starting at the last character of the string passed to the function, you build a new string `reversedStr` from `str`.
@@ -77,10 +85,4 @@ function reverseString(str) {
* Finally, you return the final value of `reversedStr`.
</details><br>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,11 +1,11 @@
---
title: Slice and Splice
---
## Slice and Splice
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
# Slice and Splice
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
---
## Problem Explanation
We need to copy each element from the first array into the second array starting at the index n. We've also got to ensure that the original arrays are not mutated. That is, we cannot make any changes to the original arrays.
@@ -14,31 +14,30 @@ We need to copy each element from the first array into the second array starting
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice' target='_blank' rel='nofollow'>Array.slice()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice' target='_blank' rel='nofollow'>Array.splice()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
Create a copy of the second array inside of the function. This will ensure that the original array is not mutated. This can be done by using the slice operation on the second array, and assign it to a variable.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
Loop through all of the items in the first array. For each item in the first array splice it into the copied array in the index given as argument.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
Increment the index after performing the splice.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](https://discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
```js
function frankenSplice(arr1, arr2, n) {
// It's alive. It's alive!
@@ -51,7 +50,7 @@ function frankenSplice(arr1, arr2, n) {
}
```
### Code Explanation:
#### Code Explanation
* Our goal is to take all of the elements from `arr1` and insert them into `arr2` starting with index position `n`. At the same time we must ensurethat neither `arr` or `arr2` have been mutated.
@@ -63,8 +62,10 @@ function frankenSplice(arr1, arr2, n) {
* Finally, we return the `localArray` and end the function.
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
## 🌻 Intermediate Code Solution:
```js
function frankenSplice(arr1, arr2, n) {
// It's alive. It's alive!
@@ -80,8 +81,4 @@ function frankenSplice(arr1, arr2, n) {
* `localArr` is returned and the function is complete.
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,9 +1,11 @@
---
title: Title Case a Sentence
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Title Case a Sentence
---
## Problem Explanation
We have to return a sentence with title case. This means that the first letter will always be in uppercase and the rest will be in lowercase.
@@ -14,50 +16,53 @@ We have to return a sentence with title case. This means that the first letter w
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-touppercase/15950' target='_blank' rel='nofollow'>JS String Prototype ToUpperCase</a>
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-replace/15942' target='_blank' rel='nofollow'>JS String Prototype Replace</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
* You should start by splitting the string into an array of words.
* Split the sentence.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
* You should make the word lowercase before making the first letter uppercase.
* Use replace method on each word to capitalize the first letter of each word.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
* You will need to create a new string with pieces of the previous one and at the end merge everything into a single string again.
* In replace method, give first argument as the position of the first letter using charAt. For second argument write a function to return the capitalized letter as the replacement.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Solution ahead!**
```js
String.prototype.replaceAt = function(index, character) {
return (
this.substr(0, index) + character + this.substr(index + character.length)
);
};
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
function titleCase(str) {
var newTitle = str.split(" ");
var updatedTitle = [];
for (var st in newTitle) {
updatedTitle[st] = newTitle[st]
.toLowerCase()
.replaceAt(0, newTitle[st].charAt(0).toUpperCase());
}
return updatedTitle.join(" ");
}
```
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
};
function titleCase(str) {
var newTitle = str.split(' ');
var updatedTitle = [];
for (var st in newTitle) {
updatedTitle[st] = newTitle[st].toLowerCase().replaceAt(0, newTitle[st].charAt(0).toUpperCase());
}
return updatedTitle.join(' ');
}
### Code Explanation:
#### Code Explanation
We are modifying the `replaceAt` function using prototype to facilitate the use of the program.
@@ -69,21 +74,23 @@ Split the string by white spaces, and create a variable to track the updated tit
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-split/15944' target='_blank' rel='nofollow'>JS String Prototype Split</a>
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-substr/15945' target='_blank' rel='nofollow'>JS String Prototype Substr</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-join/14292' target='_blank' rel='nofollow'>JS Array Prototype Join</a>
</details>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
<details><summary>Solution 2 (Click to Show/Hide)</summary>
function titleCase(str) {
var convertToArray = str.toLowerCase().split(" ");
var result = convertToArray.map(function(val){
return val.replace(val.charAt(0), val.charAt(0).toUpperCase());
});
return result.join(" ");
}
```js
function titleCase(str) {
var convertToArray = str.toLowerCase().split(" ");
var result = convertToArray.map(function(val) {
return val.replace(val.charAt(0), val.charAt(0).toUpperCase());
});
return result.join(" ");
}
titleCase("I'm a little tea pot");
titleCase("I'm a little tea pot");
```
### Code Explanation:
#### Code Explanation
We are making entire string lowercase and then converting it into array. Then we are using map function to replace the lowercase character with uppercase. Finally, we are returning the string using `join` method.
@@ -91,14 +98,17 @@ We are making entire string lowercase and then converting it into array. Then we
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-map/14294' target='_blank' rel='nofollow'>JS Array Prototype Map</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
function titleCase(str) {
return str.toLowerCase().replace(/(^|\s)\S/g, (L) => L.toUpperCase());
}
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```js
function titleCase(str) {
return str.toLowerCase().replace(/(^|\s)\S/g, L => L.toUpperCase());
}
```
### Code Explanation:
#### Code Explanation
The solution works by first lowercasing all the characters in the string and then only uppercasing the first character of each word.
- Lowercase the whole string using `str.toLowerCase()`.
@@ -119,8 +129,4 @@ The solution works by first lowercasing all the characters in the string and the
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions' target='_blank' rel='nofollow'>JS Regex Resources</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,9 +1,10 @@
---
title: Truncate a String
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Truncate a String
---
## Problem Explanation
We need to reduce the length of the string or **truncate** it if it is longer than the given maximum length specified and add `...` to the end. If it is not that long then we keep it as is.
@@ -11,50 +12,53 @@ We need to reduce the length of the string or **truncate** it if it is longer th
* <a href='https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/JS-String-Prototype-Slice' target='_blank' rel='nofollow'>String.prototype.slice()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
Strings are immutable in JavaScript so we will need a new variable to store the truncated string.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
You will need to use the slice() method and specify where to start and where to stop.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Solution ahead!**
```js
function truncateString(str, num) {
// Clear out that junk in your trunk
if (str.length > num) {
return str.slice(0, num) + "...";
} else {
return str;
}
}
```
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
function truncateString(str, num) {
// Clear out that junk in your trunk
if(str.length > num) {
return str.slice(0,num)+"...";
} else {
return str;
}
}
### Code Explanation:
#### Code Explanation
* We start off with a simple `if` statement to determine one of two outcomes...
* If our string length is greater than the `num` we want to truncate it, we return a slice of our string starting at character 0, and ending at `num`. We then append our `'...'` to the end of the string.
* However, if above situation is not true, it means our string length is less than our truncation `num`. Therefore, we can just return the string.
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
function truncateString(str, num) {
return (str.length > num)?(str.slice(0,num)+"..."):str;
}
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```js
function truncateString(str, num) {
return str.length > num ? str.slice(0, num) + "..." : str;
}
```
### Code Explanation:
#### Code Explanation
* This solution is very similar to basic solution. To determine the new string, we use a ternary operator. In our ternary operation, if `str.length` is larger than `num`, we return a new string which is slice of our string starting at character 0, and ending at `num` and the `'...'` is appended to the end of our new string. If `str.length` is less than or equal to `num`, we return the string without any truncation.
@@ -64,9 +68,4 @@ You will need to use the slice() method and specify where to start and where to
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator' target='_blank' rel='nofollow'>Conditional (ternary) Operator</a>
* <a href='https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/JS-String-Prototype-Slice' target='_blank' rel='nofollow'>String.prototype.slice()</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>

View File

@@ -1,9 +1,11 @@
---
title: Where Do I Belong
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
# Where Do I Belong
---
## Problem Explanation
This can be a tricky problem to understand. You need to find where in the array a number should be inserted by order, and return the index where it should go.
@@ -11,114 +13,119 @@ This can be a tricky problem to understand. You need to find where in the array
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-sort/14306' target='_blank' rel='nofollow'>JS Array Sort</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
---
## Hints
### Hint 1
The first thing to do is sort the array from lower to bigger, just to make the code easier. This is where sort comes in, it needs a callback function so you have to create it.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
### Hint 2
Once the array is sorted, then just check for the first number that is bigger and return the index.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
### Hint 3
If there is no index for that number then you will have to deal with that case too.
> _try to solve the problem now_
## Spoiler Alert!
---
## Solutions
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
<details><summary>Solution 1 (Click to Show/Hide)</summary>
**Solution ahead!**
```js
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
for (var a = 0; a < arr.length; a++) {
if (arr[a] >= num) return a;
}
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
return arr.length;
}
```
for (var a = 0; a < arr.length; a++) {
if (arr[a] >= num)
return a;
}
#### Code Explanation
return arr.length;
}
## Code Explanation:
* First I sort the array using `.sort(callbackFuntion)` to sort it by lowest to highest, from left to right.
* First I sort the array using `.sort(callbackFunction)` to sort it by lowest to highest, from left to right.
* Then I use a for loop to compare the items in the array starting from the smallest one. When an item on the array is greater than the number we are comparing against, then we return the index as an integer.
#### Relevant Links
* <a href='http://forum.freecodecamp.com/t/javascript-parseint/14686' target='_blank' rel='nofollow'>parseInt()</a>
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
</details>
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
var times = arr.length; // runs the for loop once for each thing in the array
var count = 0;
for (var i=0;i<times;i++){
if(num>arr[i]){count++;} } // counts how many array numbers are smaller than num
return count; // the above equals num's position in a sorted array
<details><summary>Solution 2 (Click to Show/Hide)</summary>
```js
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
var times = arr.length; // runs the for loop once for each thing in the array
var count = 0;
for (var i = 0; i < times; i++) {
if (num > arr[i]) {
count++;
}
} // counts how many array numbers are smaller than num
return count; // the above equals num's position in a sorted array
}
getIndexToIns([40, 60], 50);
getIndexToIns([40, 60], 50);
```
## Code Explanation:
#### Code Explanation
* I do not sort the arr input array
* I run a for loop counting whenever the num input is bigger than an arr input number.
* This number is equivalent to what num's position would be in a sorted array.
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
<details><summary>Solution 3 (Click to Show/Hide)</summary>
by [@HarinaPana](/u/harinapana)
```js
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
function getIndexToIns(arr, num) {
var i = 0;
while (num > arr[i]) {
i++;
}
arr.sort(function(a, b) {
return a - b;
});
return i;
}
var i = 0;
while (num > arr[i]) {
i++;
}
getIndexToIns([40, 60], 50);
```
return i;
}
getIndexToIns([40, 60], 50);
## Code Explanation:
#### Code Explanation
* Sort existing array.
* Iterate through the array while checking if _num_ is bigger.
* The loop will stop when _num_ isn't bigger than _i_ and return the last element checked.
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
</details>
by [@faustodc](/u/faustodc)
<details><summary>Solution 4 (Click to Show/Hide)</summary>
function getIndexToIns(arr, num) {
arr.push(num);
arr.sort(function(a, b){return a-b});
return arr.indexOf(num);
}
```js
function getIndexToIns(arr, num) {
arr.push(num);
arr.sort(function(a, b) {
return a - b;
});
return arr.indexOf(num);
}
```
## Code Explanation:
#### Code Explanation
* First we add the number `num` to the array using `push()` which adds it as the last element of the array.
* Then we use `sort()` with the callback function `function(a, b){return a-b}` to sort the numbers in ascending order.
@@ -130,22 +137,26 @@ by [@faustodc](/u/faustodc)
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort' target='_blank' rel='nofollow'>sort()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf' target='_blank' rel='nofollow'>indexOf()</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
</details>
<details><summary>Solution 5 (Click to Show/Hide)</summary>
**Using `.findIndex()`**
function getIndexToIns(arr, num) {
// sort and find right index
var index = arr.sort((curr, next) => curr > next)
.findIndex((currNum)=> num <= currNum);
// Returns proper answer
return index === -1 ? arr.length : index;
}
```js
function getIndexToIns(arr, num) {
// sort and find right index
var index = arr
.sort((curr, next) => curr > next)
.findIndex(currNum => num <= currNum);
// Returns proper answer
return index === -1 ? arr.length : index;
}
getIndexToIns([40, 60], 500);
getIndexToIns([40, 60], 500);
```
## Code Explanation:
#### Code Explanation
* First sort the array in ascending order, this is currently done using array functions for minimal footprint.
* Once the array it is sorted, we directly apply the `.findIndex()` where we are going to compare every element in the array until we find where `num <= currNum` meaning where the number we want to insert is less or equal to the current number number in the iteration.
@@ -157,20 +168,22 @@ by [@faustodc](/u/faustodc)
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions' target='_blank' rel='nofollow'>Arrow Functions</a>
* <a href='http://forum.freecodecamp.com/t/javascript-ternary-operator/15973' target='_blank' rel='nofollow'>Ternary Operator</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
</details>
by [@nivrith](/u/nivrith)
<details><summary>Solution 6 (Click to Show/Hide)</summary>
function getIndexToIns(arr, num) {
```js
function getIndexToIns(arr, num) {
return arr
.concat(num)
.sort((a, b) => a - b)
.indexOf(num);
}
return arr.concat(num).sort((a,b) => a-b).indexOf(num);
getIndexToIns([1, 3, 4], 2);
```
}
getIndexToIns([1,3,4],2);
## Code Explanation:
#### Code Explanation
* We use method-chaining to invoke one method after another to solve the problem in a single line. First we merge `arr` and `num` by invoking the arr.concat(num) method
* Then we use `sort()` with the callback **arrow function** `(a, b) => return a-b` to sort the numbers in ascending order
@@ -181,9 +194,4 @@ by [@nivrith](/u/nivrith)
* <a href='https://schier.co/blog/2013/11/14/method-chaining-in-javascript.html' target='_blank' rel='nofollow'>Method chaining in JavaScript</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat?v=example' target='_blank' rel='nofollow'>concat()</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions' target='_blank' rel='nofollow'>Arrow functions</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
</details>