0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Noitidart
  • 35,443
  • 37
  • 154
  • 323

2 Answers2

1

How about this?

function sharedStartByWord(array){
    var A = array.concat().sort(),
        a1 = A[0].split(/\W/), a2 = A[A.length-1].split(/\W/),
        L = a1.length, i = 0;
    while (i < L && a1[i] === a2[i]) { i++; }
    return a1.slice(0, i).join(' ');
}
Ruud
  • 1,262
  • 11
  • 14
  • Thank you so much! This works perfect! I did a jsbench comparison to @void's method - http://jsben.ch/F4HJJ - both are equal. – Noitidart Mar 06 '18 at 20:25
1
  • Split the all the array elements with a space
  • Get the first element and all the other elements
  • Compare elements of all the other elements with the first array elements. Make sure you should compare the same index.
  • If a mismatch occurrs then splice the first element array.

function sharedStartByWord(arr) {
  var A = arr.concat().map(el => el.split(" "));
  var B = A.concat();
  B.shift();

  var words = A[0];
  var wordsTORemove = [];

  A[0].forEach((el, i) => {
    B.forEach(_el => {
      if (el !== _el[i])
        words.splice(i, 1);
    })
  })

  return words.join("");
}

var x = sharedStartByWord(['Noitidart Sab', 'Noitidart Saber', 'Noitidart Something']);
console.log(x);
void
  • 36,090
  • 8
  • 62
  • 107
  • Thank you void so much! This is really cool. I accepted @rudd answer because he has less score, but your solution is equally or even better! I created a jsben comparing the two methods - http://jsben.ch/F4HJJ - both seem equal. – Noitidart Mar 06 '18 at 20:25