Blog

JavaScript Function to Find the Longest Common Prefix
Posted on July 20, 2015 in Algorithms, JavaScript by Matt Jennings

In a JavaScript array, find the longest common prefix of all array elements.

function longestCommonPrefix(arr){
    // sort() method arranges array elements alphabetically
    var sortArr = arr.sort();
    
    // Get first array element    
    var arrFirstElem = arr[0];
  
    // Get the last array element length minus one
    var arrLastElem = sortArr[sortArr.length - 1]; 
    
    // Get first array element length
    var arrFirstElemLength = arrFirstElem.length; 
    
    // Set "i" incrementer to 0
    var i= 0;
    
    // while "i" is less than the length of the first array element AND
    // the first array element character position matches the last array character position
    // increment "i" by one
    while(i < arrFirstElemLength && arrFirstElem.charAt(i) === arrLastElem.charAt(i)) {
      i++;
    }
    
    // Console log the substring of the first element of the array starting with
    // index zero and going all the way to just below index "i"
    console.log(arrFirstElem.substring(0, i));
}


var x = ["internetly", "internet", "internets"];
var y = ["a", "c", "b"];

// Output for line below is:
// "internet"
longestCommonPrefix(x);

// Output for line below is:
// ""
longestCommonPrefix(y);

Leave a Reply