find common prefix in a list of words in javascript

One way to find the common prefix in a list of words in JavaScript is to loop through the characters of the first word and compare them with the corresponding characters in the rest of the words. When a character in any of the words does not match, we know that the common prefix ends at the previous character.

Here's the code to do this:

index.tsx
function findCommonPrefix(words) {
  if (words.length === 0) {
    return '';
  }
  
  const firstWord = words[0];
  let prefix = '';
  
  for (let i = 0; i < firstWord.length; i++) {
    const char = firstWord[i];
    
    for (let j = 1; j < words.length; j++) {
      if (i >= words[j].length || words[j][i] !== char) {
        return prefix;
      }
    }
    
    prefix += char;
  }
  
  return prefix;
}
411 chars
23 lines

This function takes an array of words as input and returns the common prefix as a string. We first check if the input array is empty and return an empty string in that case. We then assume that the first word is the common prefix and loop through its characters. For each character, we compare it with the corresponding character in the rest of the words. If a character does not match or we reach the end of a word, we return the prefix. If all characters match, we add the character to the prefix and continue to the next character. Finally, we return the prefix.

gistlibby LogSnag