Created
December 26, 2019 02:34
-
-
Save Nicknyr/76566112e32899f61a7f75c42bd5d728 to your computer and use it in GitHub Desktop.
Code Signal - All Largest Strings 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
/* | |
Given an array of strings, return another array containing all of its longest strings. | |
Example | |
For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be | |
allLongestStrings(inputArray) = ["aba", "vcd", "aba"]. | |
*/ | |
function allLongestStrings(inputArray) { | |
let answers = inputArray; | |
// Sort array largest to smallest by length | |
answers.sort((a, b) => { | |
return b.length - a.length; | |
}); | |
// Iterate through array, once the next element has a smaller length than the // current element remove that element and all elements after it | |
// Only the elements equal to the largest element will get kept | |
for(let i = 0; i < answers.length - 1; i++) { | |
if(answers[i].length > answers[i + 1].length) { | |
answers.splice(i + 1); | |
} | |
} | |
return answers; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment