-
Notifications
You must be signed in to change notification settings - Fork 0
Algorithm Mutations
- 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..
- If everything is lowercase it will be easier to compare.
- Our strings might be easier to work with if they were arrays of characters.
- A loop might help. Use
indexOf()to check if the letter of the second word is on the first.
Solution ahead!
function mutation(arr) {
var test = arr[1].toLowerCase();
var target = arr[0].toLowerCase();
for (i=0;i<test.length;i++) {
if (target.indexOf(test[i]) < 0)
return false;
}
return true;
}🚀 Run Code
function mutation(arr) {
return arr[1].toLowerCase()
.split('')
.every(function (letter){
return arr[0].toLowerCase()
.indexOf(letter) != -1;
});
}🚀 Run Code
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.
If they are all found, the loop will finish without returning anything and we get to return true.
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 using indexOf on the first string. indexOf will give you -1 if the current letter is missing. We check that not to be the case, for if this happens even once every will be false.
If you found this page useful, you can give thanks by copying and pasting this on the main chat: Thanks @sxmxc @Rafase282 @anuragaryan @hallaathrad for your help with Algorithm: Mutations
NOTE: Please add your username only if you have added any relevant main contents to the wiki page. (Please don't remove any existing usernames.)
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links