Created
July 20, 2020 23:09
-
-
Save cormac0108/d8adf761ee02e08b61bcb69343bfd014 to your computer and use it in GitHub Desktop.
ZTM 2020 Clean the room challenge
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
// Question 1: Clean the room function: given an input of [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20], | |
// make a function that organizes these into individual array that is ordered. For example | |
// answer(ArrayFromAbove) should return: [[1,1,1,1],[2,2,2], 4,5,10,[20,20], 391, 392,591]. | |
// Bonus: Make it so it organizes strings differently from number types. i.e. [1, "2", "3", 2] | |
// should return [[1,2], ["2", "3"]] | |
function clean(arr) { | |
let i = 0; | |
let pos = 0; | |
let duplicateArray = []; | |
let newArray = []; | |
arr.sort((a, b) => a - b); | |
while (i < arr.length) { | |
if ( arr[0] === arr[1] ) { | |
pos = arr.lastIndexOf(arr[0]) + 1; | |
duplicateArray = arr.splice(0, pos); | |
newArray.push(duplicateArray); | |
} else { | |
newArray.push(arr[0]); | |
arr.shift(); | |
} | |
} | |
return newArray; | |
} | |
console.log(clean([1,2,4,591,392,391,2,5,10,2,1,1,1,20,20])); | |
// thank Luckerella for the code. https://gist.github.com/Luckerella |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment