-
-
Save redrambles/78c7819943502730406bd523e4e7d487 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
const wordArray = ['cranberry', 'crawfish', 'crap']; | |
const longestPrefix = (wordArray) => { | |
// Find the smallest word - our prefix cannot be any longer | |
const smallestWord = wordArray.reduce((acc, word) => { | |
return word.length <= acc.length ? word : acc; | |
}); | |
let indexNoMatch = []; | |
for (let word of wordArray) { | |
for (let i = 0; i < smallestWord.length; i++) { | |
if (word[i] !== smallestWord[i]) { | |
indexNoMatch.push(i); | |
} | |
} | |
} | |
// Grab smallest number in indexNoMatch array - that's where the common letters for all words end | |
const smallestNumber = indexNoMatch.reduce((acc, num) => { | |
return num <= acc ? num : acc; | |
}); | |
const commonPrefix = smallestWord | |
.split('') | |
.splice(0, smallestNumber) | |
.join(''); | |
console.log(commonPrefix); | |
}; | |
longestPrefix(wordArray); // "cra" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment