I came across this amazing sharedStart function in a challenge. You can find it here:
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 function works on a per-character basis.
For example, using the function 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 '
Nevertheless, I am interested in performing the comparison by word instead of character. In that case, the expected results should be as follows:
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 have attempted to come up with my own solution, but it has become quite convoluted. It's so bad that I feel embarrassed to share it as part of the question. Can someone please guide me on how to create a sharedStartByWord
version?