Skip to content

Instantly share code, notes, and snippets.

@duggiemitchell
Last active January 5, 2016 18:43
Show Gist options
  • Select an option

  • Save duggiemitchell/03564ce5ae42bfd7e7d4 to your computer and use it in GitHub Desktop.

Select an option

Save duggiemitchell/03564ce5ae42bfd7e7d4 to your computer and use it in GitHub Desktop.
Traversing Array to strings using indexOf()
// Bonfire: Mutations
// Author: @duggiemitchell
// Challenge: http://www.freecodecamp.com/challenges/bonfire-mutations
// Learn to Code at Free Code Camp (www.freecodecamp.com)
//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.
function mutation(arr) {
var strOne = arr[0].toLowerCase();
var strTwo = arr[1].toLowerCase().split("");
return strTwo.every(function(chr) {
return strOne.indexOf(chr) !== -1;
});
}
console.log(mutation(["hello", "Hey"]));

I hate for loops so this is a less verbose solution to traverse objects. It was unnecessary to convert the first index of the array into a string if comparing characters within the second index.

var strOne = arr[0].toLowerCase(); // first index of array to lowercase
var strTwo = arr[1].toLowerCase().split(""); // second index to lowercase, then split to an array
``console.log(strTwo); // output is ["h", "e","l"]

return strTwo.every(function(chr) { // every() executes a callback until it returns a false or true if all elements are present.
``return strOne.indexOf(chr) !== -1; //indexOf returns false if the value to search is not present.

}); } console.log(mutation(["hello", "Hel"]));
@duggiemitchell
Copy link
Copy Markdown
Author

I hate for loops so this is a less verbose solution to traverse objects. It was unnecessary to convert the first index of the array into a string if comparing characters within the second index.

var strOne = arr[0].toLowerCase(); // first index of array to lowercase
var strTwo = arr[1].toLowerCase().split(""); // second index to lowercase, then split to an array
``console.log(strTwo); // output is ["h", "e","l"]

return strTwo.every(function(chr) { // every() executes a callback until it returns a false or true if all elements are present.
``return strOne.indexOf(chr) !== -1; //indexOf returns false if the value to search is not present.

}); } console.log(mutation(["hello", "Hel"]));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment