Created
September 3, 2021 20:11
-
-
Save PradatiusD/9a3f34f480b1c380db5714c2119885b7 to your computer and use it in GitHub Desktop.
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
/** | |
* Write a function to find the longest common prefix string in an array of strings. | |
* -------------------------------- | |
* Function to find matching characters and stop at the | |
* point at which they are different or if the string ends | |
* | |
* Worked with https://twitter.com/Spraggsz_ to solve! | |
* @return {string} | |
*/ | |
function longestPrefix (arrayOfStrings) { | |
let string = '' | |
let shortestStringLength = null | |
for (const array of arrayOfStrings) { | |
const isSmaller = shortestStringLength === null || shortestStringLength > array.length | |
if (isSmaller) { | |
shortestStringLength = array.length | |
} | |
} | |
for (let i = 0; i < shortestStringLength; i++) { | |
// compare all arrayOfStrings[i] to see if they are equal | |
const firstChar = arrayOfStrings[0][i] | |
for (let j = 1; j < arrayOfStrings.length; j++) { | |
if (firstChar !== arrayOfStrings[j][i]) { | |
return string | |
} | |
} | |
string += firstChar | |
} | |
return string | |
} | |
longestPrefix([ | |
"parrot", | |
"poodle", | |
"fish" | |
]) | |
// '' | |
longestPrefix([ | |
"cranberries", | |
"crawfish", | |
"crap" | |
]) | |
// 'cra' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment