- To make solving problems easier, it can be helpful to break them down into many chunks. Then, each chunk can be solved one by one.
- For example, if you are building a calculator, don't try to solve the problem as a whole. First, consider how to get inputs. Then, determine each arithmetic operation one by one. Finally, display the results.
function convertToF(celsius) {
let fahrenheit;
fahrenheit = celsius * 9/5 + 32;
return fahrenheit;
}
console.log(convertToF(30));
-
Reverse the provided string.
-
You may need to turn the string into an array before you can reverse it.
-
Your result must be a string.
function reverseString(str) {
let temp ="";
for (let i=0;i<str.length; i++){
temp = str[i]+ temp;
}
str = temp;
return str;
}
console.log(reverseString("hello"));
function reverseString(str) {
for (var reversedStr = "", i = str.length - 1; i >= 0; i--) {
reversedStr += str[i];
}
return reversedStr;
}
-
Starting at the last character of the string passed to the function, you build a new string
reversedStr
fromstr
. -
During each iteration of the
for
loop,reversedStr
gets concatenated with itself and the current character. -
Finally, you return the final value of
reversedStr
.
function reverseString(str) {
return str
.split("")
.reverse()
.join("");
}
-
Our goal is to take the input,
str
, and return it in reverse. Our first step is to split the string by characters usingsplit('')
. Notice that we don’t leave anything in between the single quotes, this tells the function to split the string by each character. -
Using the
split()
function will turn our string into an array of characters, keep that in mind as we move forward. -
Next we chain the
reverse()
function, which takes our array of characters and reverses them. -
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.
-
Return the factorial of the provided integer.
-
If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.
-
Factorials are often represented with the shorthand notation
n!
-
For example:
5! = 1 * 2 * 3 * 4 * 5 = 120
-
Only integers greater than or equal to zero will be supplied to the function.
function factorialize(num) {
if (num > 0) {
let sum =1;
for (let i = 1; i <= num; i++) {
sum = sum * i;
}
num = sum;
return num;
} else {
return 1;
}
}
factorialize(5);
function factorialize(num) {
for (var product = 1; num > 0; num--) {
product *= num;
}
return product;
}
factorialize(5);
-
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 sinceproduct
is initialized as 1, it will have the correct value when thereturn
statement is executed. -
For all numbers passed to the function which are greater than one, the simple
for
loop will decrementnum
by one each iteration and recalculateproduct
down to the value1
.
function factorialize(num) {
if (num === 0) {
return 1;
}
return num * factorialize(num - 1);
}
factorialize(5);
- 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 Stack Overflow
function factorialize(num, factorial = 1) {
if (num == 0) {
return factorial;
} else {
return factorialize(num - 1, factorial * num);
}
}
factorialize(5);
-
In this solution, we use Tail Recursion 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 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.
function factorialize(num, factorial = 1) {
return num < 0 ? 1 : (
new Array(num)
.fill(undefined)
.reduce((product, val, index) => product * (index + 1), 1)
);
}
factorialize(5);
- In this solution, we used “reduce” function to find the factorial value of the number.
- We have created an array which has length
num
. And we filled all elements of the array asundefined
. In this case, we have to do this because empty arrays couldn’t reducible. You can fill the array as your wish by the way. This depends on your engineering sight completely. - In
reduce
function’s accumulator is callingproduct
this is also our final value. We are multiplying our index value with the product to findfactorial
value. - We’re setting product’s initial value to 1 because if it was zero products gets zero always.
- Also the factorial value can’t calculate for negative numbers, first of all, we’re testing this.
- Return the length of the longest word in the provided sentence. Your response should be a number.
function findLongestWordLength(str) {
var words = str.split(' ');
var maxLength = 0;
for (var i = 0; i < words.length; i++) {
if (words[i].length > maxLength) {
maxLength = words[i].length;
}
}
return maxLength;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");
-
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.
-
Then check for the longest word by comparing the current word to the previous one and storing the new longest word. At the end of the loop just return the number value of the variable maxLength.
function findLongestWordLength(s) {
return s.split(' ')
.reduce(function(x, y) {
return Math.max(x, y.length)
}, 0);
}
- For more information on reduce click here.
- In case you’re wondering about that 0 after the callback function, it is used to give an initial value to the x, so that Math.max will know where to start.
function findLongestWordLength(str) {
return Math.max(...str.split(" ").map(word => word.length));
}
-
We provide
Math.max
with the length of each word as argument, and it will simply return the highest of all. -
Let’s analyze everything inside the
Math.max
parenthesees to understand how we do that. -
str.split(" ")
splits the string into an array, taking spaces as separators. It returns this array: [“The”,"quick,“brown”,“fox”,“jumped”,“over”,“the”,“lazy”,“dog”]. -
Then, we will make another array, made from the lengths of each element of the
str.split(" ")
array withmap()
. -
str.split(" ").map(word => word.length)
returns [3, 5, 5, 3, 6, 4, 3, 4, 3] -
Finally, we pass the array as argument for the Math.max function with the spread operator
...
-
For more information on map click here.
function findLongestWordLength(str) {
//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;
}
//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(" "));
}
}
- Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
- Remember, you can iterate through an array with a simple for loop, and access each member with array syntax
arr[i]
. - largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27, 5, 39, 1001].
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;
}
return results;
}
- Create a variable to store the results as an array.
- Create an outer loop to iterate through the outer array.
- Create a second variable to hold the largest number and initialise it with the first number. This must be outside an inner loop so it won’t be reassigned until we find a larger number.
- Create said inner loop to work with the sub-arrays.
- Check if the element of the sub array is larger than the currently stored largest number. If so, then update the number in the variable.
- After the inner loop, save the largest number in the corresponding position inside of the results array.
- And finally return said array.
function largestOfFour(arr) {
return arr.map(function(group) {
return group.reduce(function(prev, current) {
return current > prev ? current : prev;
});
});
}
- 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()
- the callback function passed to the reduce method takes the previous value and the current value and compares the two values
- if the current value is higher than the previous value we set it as the new previous value for comparison with the next item within the array or returns it to the map method callback if it’s the last item
function largestOfFour(arr) {
return arr.map(Function.apply.bind(Math.max, null));
}
-
TL;DR: We build a special callback function (using the
Function.bind
method), that works just likeMath.max
but also hasFunction.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.
-
So we want to create a function that does the work of
Math.max
and accepts input as an array (which by it doesn’t by default). -
In other words, it would be really nice and simple if this worked by itself:
Math.max([9, 43, 20, 6]); // Resulting in 43
-
Alas, it doesn’t.
- To do the work of accepting arguments in the shape of an array, there is this
Function.prototype.apply
method, but it complicates things a bit by invoking the context function.
- To do the work of accepting arguments in the shape of an array, there is this
-
i.e.
Math.max.apply(null, [9, 43, 20, 6])
; would invoke something like aMax.max
method. What we’re looking for… almost. -
Here we’re passing
null
as the context of theFunction.prototype.apply
method asMath.max
doesn’t need any context.- Since
arr.map
expects a callback function, not just an expression, we create a function out of the previous expression by using theFunction.bind
method. - Since,
Function.prototype.apply
is a static method of the sameFunction
object, we can callFunction.prototype.bind
onFunction.prototype.apply
i.e.Function.prototype.apply.bind
. - Now we pass the context for the
Function.prototype.apply.bind
call (in this case we wantMath.max
so we can gain its functionality). - Since the embedded
Function.prototype.apply
method will also require a context as it’s 1st argument, we need to pass it a bogus context.-
So, we pass
null
as the 2nd param toFunction.prototype.apply.bind
which gives a context to theMath.max
method. -
Since,
Math.max
is independent of any context, hence, it ignores the bogus context given byFunction.prototype.apply
method call. -
Thus, our
Function.prototype.apply.bind(Math.max, null)
makes a new function accepting the arr.map values i.e. the inner arrays.
-
- Since
-
Relevant Links
function largestOfFour(arr, finalArr = []) {
return !arr.length
? finalArr
: largestOfFour(arr.slice(1), finalArr.concat(Math.max(...arr[0])))
}
-
Check if a string (first argument,
str
) ends with the given target string (second argument,target
). -
This challenge can be solved with the
.endsWith()
method, which was introduced in ES2015. But for the purpose of this challenge, we would like you to use one of the JavaScript substring methods instead.
function confirmEnding(str, target) {
return str.slice(str.length - target.length)=== target;
}
confirmEnding("Bastian", "n");
- First we use the
slice
method copy the string. - In order to get the last characters in
str
equivalent to thetarget
's length we use theslice
method. - The first parameter inside the
slice
method is the starting index and the second parameter would be the ending index. - For example
str.slice(10, 17)
would returngive me
. - In this case we only include one parameter which it will copy everything from the starting index.
- We substract the length of
str
and the length oftarget
, that way, we shall get the last remaining characters equivalent to thetarget
's length. - Finally we compare the return result of slice to
target
and check if they have the same characters.
function confirmEnding(str, target) {
let re = new RegExp(target + "$", "i");
return re.test(str);
}
console.log(confirmEnding("Bastian", "n"));
- We need to make a pattern from the
target
variable that exists at the end of the stringstr
. - 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.
- Repeat a given string
str
(first argument) fornum
times (second argument). Return an empty string ifnum
is not a positive number.
function repeatStringNumTimes(str, num) {
let arr = ""
if (num > 0) {
for (let i = 0; i < num; i++ ) {
arr += str;
}
} else {
arr ="";
}
return arr;
}
repeatStringNumTimes("abc", 3);
function repeatStringNumTimes(str, num) {
var accumulatedStr = "";
while (num > 0) {
accumulatedStr += str;
num--;
}
return accumulatedStr;
}
function repeatStringNumTimes(str, num) {
if (num < 1) {
return "";
} else if (num === 1) {
return str;
} else {
return str + repeatStringNumTimes(str, num - 1);
}
}
- This solution uses recursion.
- We check if
num
is negative and return an empty string if true. - Then we check if it’s equal to 1 and in that case we return the string itself.
- If not, we add the string to a call of our function with
num
being decreased by 1, which will add anotherstr
and another… until eventuallynum
is 1. And return that whole process.
function repeatStringNumTimes(str, num) {
return num > 0 ? str.repeat(num) : "";
}
repeatStringNumTimes("abc", 3);
function repeatStringNumTimes(str, num) {
return num > 0 ? str + repeatStringNumTimes(str, num - 1) : '';
}
- Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a
...
ending.
function truncateString(str, num) {
if (num >= str.length){
return str;
} else {
return str.slice(0,num)+"...";
}
}
truncateString("A-tisket a-tasket A green and yellow basket", 8);
function truncateString(str, num) {
return num >= str.length ? str:str.slice(0,num)+"...";
}
truncateString("A-tisket a-tasket A green and yellow basket", 8);
function truncateString(str, num) {
// Clear out that junk in your trunk
if (str.length > num) {
return str.slice(0, num) + "...";
} else {
return str;
}
}
- 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 atnum
. 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.
function truncateString(str, num) {
return str.length > num ? str.slice(0, num) + "..." : str;
}
- 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 thannum
, we return a new string which is slice of our string starting at character 0, and ending atnum
and the'...'
is appended to the end of our new string. Ifstr.length
is less than or equal tonum
, we return the string without any truncation. m - NOTE In order to understand the above code, you need to understand how a Ternary Operator works. The Ternary Operator is frequently used as a shortcut for the
if
statement and follows this format:condition ? expr1 : expr2
. If thecondition
evaluates to true, the operator returns the value ofexpr1
. Otherwise, it returns the value ofexpr2
.
- Create a function that looks through an array (first argument) and returns the first element in the array that passes a truth test (second argument). If no element passes the test, return undefined.
findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })
should return 8.findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })
should return undefined.
function findElement(arr, func) {
let num = 0;
for (var i = 0; i < arr.length; i++) {
num = arr[i];
if (func(num)) {
return num;
}
}
return undefined;
}
findElement([1, 2, 3, 4], num => num % 2 === 0);
- 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.
function findElement(arr, func) {
return arr.find(func);
}
function findElement(arr, func) {
return arr[arr.map(func).indexOf(true)];
}
- Look through the array given in the 1st paramater “arr” using the .map() method
- Use the function in the 2nd parameter as the callback function in arr.map()
- Acquire the index of the first number that meets the condition in the function.
- Use that index to display the first available number that meets the condition.
- Check if a value is classified as a boolean primitive. Return true or false.
- booWho(true) should return true.
- booWho(false) should return true.
- booWho(NaN) should return false.
- booWho("true") should return false.
function booWho(bool) {
return typeof bool === "boolean";
}
booWho(null);
-
Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.
-
For the purpose of this exercise, you should also capitalize connecting words like "the" and "of".
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(" ");
}
titleCase("I'm a little tea pot");
-
We are modifying the
replaceAt
function using prototype to facilitate the use of the program. -
Split the string by white spaces, and create a variable to track the updated title. Then we use a loop to turn turn the first character of the word to uppercase and the rest to lowercase. by creating concatenated string composed of the whole word in lowercase with the first character replaced by its uppercase.
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");
function titleCase(str) {
return str.toLowerCase().replace(/(^|\s)\S/g, L => L.toUpperCase());
}
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()
. -
Replace every word’ first character to uppercase using
.replace
. -
Search for character at the beginning of each word i.e. matching any character following a
space
or matching the first character of the whole string, by using the following pattern. -
Regex explanation:
-
Find all non-whitespace characters
(\S)
-
At the beginning of string
(^)
-
Or after any whitespace character
(\s)
- The
g
modifier searches for other such word pattern in the whole string and replaces them. - This solution works with national symbols and accented letters as illustrated by following examples
international characters
: ‘бабушка курит трубку’ // -> ‘Бабушка Курит Трубку’accented characters
: ‘località àtilacol’ // -> ‘Località Àtilacol’
- The
- You are given two arrays and an index. Use the array methods
slice
andsplice
to copy each element of the first array into the second array, in order. Begin inserting elements at indexn
of the second array. Return the resulting array. The input arrays should remain the same after the function runs. frankenSplice([1, 2, 3], [4, 5], 1)
should return[4, 1, 2, 3, 5]
.frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)
should return["head", "shoulders", "claw", "tentacle", "knees", "toes"]
.- The first and second arrays should remain the same after the function runs.
function frankenSplice(arr1, arr2, n) {
let localArray = arr2.slice();
for (let i = 0; i < arr1.length; i++) {
localArray.splice(n, 0, arr1[i]);
n++;
}
return localArray;
}
frankenSplice([1, 2, 3] , [4, 5, 6], 1);
-
Our goal is to take all of the elements from
arr1
and insert them intoarr2
starting with index position n. At the same time we must ensure that neitherarr
orarr2
have been mutated. -
Using the
slice()
function we can create an exact replica of arr2 and assign the result of the operation to a variable,localArray
. -
Now that we have an array that we can mutate on, we can iterate through every item in the first array. For each item in the first array we can use the
splice()
function to insert the item into index n oflocalArray
. -
We increment the index n by one. This will ensure that every item from the
arr1
is inserted intolocalArray
in the proper index position. -
Finally, we return the
localArray
and end the function.
function frankenSplice(arr1, arr2, n) {
let localArr = arr2.slice();
localArr.splice(n, 0, ...arr1);
return localArr;
}
-
Since our goal is to return the new array with out altering
arr1
orarr2
we create alocalArr
and add all the items fromarr2
using theslice()
function -
Since the
splice()
function will mutate (alter) arrays and can be used to add new elements we will use it to add the contents ofarr1
intolocalArr
. n is the starting position where our content will be inserted. We won’t be deleting any elements so the next argument is0
. Then we add the entire contents ofarr1
using spread syntax .... -
localArr
is returned and the function is complete.
-
Remove all falsy values from an array.
-
Falsy values in JavaScript are
false
,nul
l,0
,""
,undefined
, andNaN
. -
Hint: Try converting each value to a Boolean.
-
Relevant Links: Falsy Values
function bouncer(arr) {
let newArray = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i]) newArray.push(arr[i]);
}
return newArray;
}
bouncer([7, "ate", "", false, 9]);
function bouncer(arr) {
return arr.filter(Boolean);
}
- The
Array.prototype.filter
method expects a function that returns aBoolean
value which takes a single argument and returnstru
e for truthy value orfalse
for falsy value. Hence we pass the built-inBoolean
function.
- Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.
- For example,
getIndexToIns([1,2,3,4], 1.5)
should return1
because it is greater than1
(index 0), but less than2
(index 1). - Likewise,
getIndexToIns([20,3,5], 19)
should return2
because once the array has been sorted it will look like[3,5,20]
and19
is less than20
(index 2) and greater than5
(index 1).
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
for (var a = 0; a < arr.length; a++) {
if (arr[a] >= num) return a;
}
return arr.length;
}
- 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.
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);
- 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.
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
var i = 0;
while (num > arr[i]) {
i++;
}
return i;
}
getIndexToIns([40, 60], 50);
function getIndexToIns(arr, num) {
arr.push(num);
arr.sort(function(a, b) {
return a - b;
});
return arr.indexOf(num);
}
- First we add the number
num
to the array usingpush()
which adds it as the last element of the array. - Then we use
sort()
with the callback functionfunction(a, b){return a-b}
to sort the numbers in ascending order. - Lastly we return the postion or index of
num
in the array with theindexOf()
function.
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);
- 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 wherenum <= currNum
meaning where the number we want to insert is less or equal to the current number number in the iteration. - Then we use ternary operations to check whether we got an index returned or
-1
. We only get-1
when the index was not found meaning when we get a false for all elements int he array, and for such case, it would mean thatnum
should be inserted at the end of the list hence why we usearr.length
. - Array.findIndex()
- Arrow Functions
function getIndexToIns(arr, num) {
return arr
.concat(num)
.sort((a, b) => a - b)
.indexOf(num);
}
getIndexToIns([1, 3, 4], 2);
function getIndexToIns(arr, num) {
return arr.filter(val => num > val).length;
}
- 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.
mutation(["hello", "Hello"])
should return true.mutation(["hello", "neo"])
should return false.
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;
}
- First we make the two strings in the array lowercase.
test
will hold what we are looking for intarget
. - Then we loop through our test characters and if any of them is not found we
return false
. - If they are all found, the loop will finish without returning anything and we get to
return true
.
function mutation(arr) {
return arr[1]
.toLowerCase()
.split("")
.every(function(letter) {
return arr[0].toLowerCase().indexOf(letter) != -1;
});
}
-
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.
-
Every
will basically give you letter by letter to compare, which we do by usingindexOf
on the first string.indexOf
will give you -1 if the currentletter
is missing. We check that not to be the case, for if this happens even onceevery
will be false.
function mutation([ target, test ], i = 0) {
target = target.toLowerCase();
test = test.toLowerCase();
return i >= test.length
? true
: !target.includes(test[i])
? false
: mutation([ target, test ], i + 1);
}
- Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.
function chunkArrayInGroups(arr, size) {
var newArray = [];
for (var i = 0; i < arr.length; i += size) {
newArray.push(arr.slice(i, i+size));
}
return newArray;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
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. Note that this for loop does not loop through arr. Instead, we are using the loop to generate numbers we can use as indices to slice the array in the right locations. Inside our loop, we create each chunk using arr.slice(i, i+size), and add this value to arr2 with arr2.push(). Finally, we return the value of arr2.
function chunkArrayInGroups(arr, size) {
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;
}
- Firstly, we create two empty arrays called
temp
andresult
, 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. - Inside our loop, we push to
temp
usingtemp.push(arr[a])
; if the remainder ofa / size
is not equal tosize - 1
. - Otherwise, we push to
temp
, pushtemp
to theresult
variable and resettemp
to an empty array. - Next, if
temp
isn’t an empty array, we push it toresult
. - Finally, we return the value of
result
.