Longest common prefix I have made a function for finding the longest common prefix for the challenge on the leetcode site. This is the code:

var longestCommonPrefix = function(strs) {
    let longestPrefix = '';
    if (strs.length &gt; 0) {
      longestPrefix = strs[0];
      for (let i = 1; i &lt; strs.length; i++) {
        for (let j = 0; j &lt; longestPrefix.length; j++) {
          if (strs[i][j] != longestPrefix[j]) {
            longestPrefix = longestPrefix.slice(0, j);
            break;
          }
        }
      }
    }

    return longestPrefix;
};


I am sure there is a way to make this code better, but not sure how to do that. Would appreciate any help.
I would find the alphabetically smallest and largest string and just run your algorithm on these two. That would avoid the embedded loop.

var longestCommonPrefix = function(strs) {
    if (!strs)
        return '';

    let smallest = strs.reduce( (min, str) =&gt; min &lt; str ? min : str, strs[0] );
    let largest  = strs.reduce( (min, str) =&gt; min &gt; str ? min : str, strs[0] );

    for (let i=0; i&lt;smallest.length; i++) {
        if (smallest[i] != largest[i])
            return smallest.substr(0,i);
    }

    return '';
};


In answer to konijn it would be minimally faster to get the smallest/largest by doing:

let smallest = strs[0];
let largest  = strs[0];
for (let i=1; i&lt;strs.length; i++) {
  let s= strs[i];
  if (s &gt; largest)  largest = s;
  if (s &lt; smallest) smallest = s;
}