leetcode : Longest Common Prefix : simple JavaScript solution
This is not the fastest solution’s by far, but I think that it is one of the more simple ones to understand.
var longestCommonPrefix = function(strs) {
if(!strs[0]){return ""} //empty array case
let lcp = "" //base case
//lcp can never be greater then first string
//so we can use it as the max length of our loop
for(i=0;i<strs[0].length;i++){
let c=strs
.map(s=>s[i]) //get all the i'th index letters
//get all the unique letters gathered in map
.reduce((arr,char)=> arr.includes(char) ? arr : [...arr,char], [])
if(c.length === 1){lcp += c[0]} //if unique letters == 1, keep looping
else{break} //else loop is over
}
return lcp
};