I was using this awesome sharedStart function from this challenge - https://stackoverflow.com/a/1917041/1828637
function sharedStart(array){
var A= array.concat().sort(),
a1= A[0], a2= A[A.length-1], L= a1.length, i= 0;
while(i<L && a1.charAt(i)=== a2.charAt(i)) i++;
return a1.substring(0, i);
}
However this does it by character.
So this following example returns Noitidart Sab
:
sharedStart(['Noitidart Sab', 'Noitidart Saber']) //=> 'Noitidart Sab'
sharedStart(['Noitidart Sab', 'Noit']) //=> 'Noit'
sharedStart(['Noitidart Sab', 'Noitidart Saber', 'Noit']) //=> 'Noit'
sharedStart(['Noit Sab bye', 'Noit Sab hi there']) //=> 'Noit Sab '
However I want to do it by word. So I should get these results:
sharedStartWords(['Noitidart Sab', 'Noitidart Saber']) //=> 'Noitidart'
sharedStartWords(['Noitidart Sab', 'Noit']) //=> '' // for no match
sharedStartWords(['Noitidart Sab', 'Noitidart Saber', 'Noit']) //=> '' // no match
sharedStartWords(['Noit Sab bye', 'Noit Sab hi there']) //=> 'Noit Sab'
I tried my best, and my solutions are so convoluted. I know this is not good in a question, I should show what I did, but it is so bad it's embarrassing.
How can I come up with a sharedStartByWord
version?