Created
July 31, 2016 19:53
-
-
Save anonymous/215757f1a8e8b9f18707b79c579d2932 to your computer and use it in GitHub Desktop.
https://repl.it/CU9P/145 created by sethopia
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
SPECIAL SNOWFLAKES | |
Create a function that takes 3 arrays of mixed elements and returns an array of only elements that are unique to the arrays | |
eg) | |
snowflake(['dog','cat','mouse'], [3, 'dog'], ['cat', 2, 1]) ==> [3,2,1,'mouse']; | |
*/ | |
function snowflake() { | |
var returnArr = []; | |
var arrays = arguments; | |
for (var array = 0; array < arrays.length; array++) { | |
var thisArray = arrays[array]; | |
for (var index = 0; index < thisArray.length; index++) { | |
var uniqueElement = true; | |
if (thisArray.indexOf(thisArray[index]) !== thisArray.lastIndexOf(thisArray[index])) uniqueElement = false; | |
var arrayToCheck = 0; | |
while (uniqueElement && arrayToCheck < arrays.length) { | |
if (arrayToCheck !== array && arrays[arrayToCheck].indexOf(thisArray[index]) > -1) { | |
uniqueElement = false; | |
} | |
arrayToCheck++; | |
} | |
if (uniqueElement) { | |
returnArr.push(thisArray[index]); | |
} | |
} | |
} | |
return returnArr; | |
} | |
// A more elegant second attempt is below, arrived at after discussion with Will Jacobson, the instructor. | |
function snowflake2() { | |
var returnArr = []; | |
var flatArr = []; | |
var arrays = arguments; | |
for (var array = 0; array < arrays.length; array++) { | |
var thisArray = arrays[array]; | |
for (var index = 0; index < thisArray.length; index++) { | |
flatArr.push(thisArray[index]); | |
} | |
} | |
for (var i = 0; i < flatArr.length; i++) { | |
if (flatArr.indexOf(flatArr[i]) === flatArr.lastIndexOf(flatArr[i])) returnArr.push(flatArr[i]); | |
} | |
return returnArr; | |
} | |
console.log(snowflake(['dog','cat','mouse'], [3, 'dog'], ['cat', 2, 1], ['zebra',5], [4, 4])); | |
console.log(snowflake2(['dog','cat','mouse'], [3, 'dog'], ['cat', 2, 1], ['zebra',5], [4, 4])); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Native Browser JavaScript |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment