JSFiddle - React, Tailwind, and code Playground

by alexisowl

HTML

<pre id="output"></pre>

JavaScript

function commonPrefix(words) {
  max_word = words.reduce(function(a, b) { return a > b ? a : b });
  prefix   = words.reduce(function(a, b) { return a > b ? b : a }); // min word

  while(max_word.indexOf(prefix) != 0) {
    prefix = prefix.slice(0, -1);
  }

  return prefix;
}


res1 = commonPrefix(['prefixA', 'prefixB', 'prefixC']);
res2 = commonPrefix(['single string']);
res3 = commonPrefix(['a', 'ba']); // should be blank


document.getElementById("output").innerHTML += 
  "res1: " + res1 + 
  "\n" +
  "res2: " + res2 +
  "\n" +
  "res3: " + res3;