Guest User

Untitled

a guest
Jan 22nd, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.58 KB | None | 0 0
  1. var longestCommonPrefix = function(strs) {
  2. const firstWord = strs[0];
  3. const arrResults = [];
  4. let index = 1;
  5. let arrWithoutFirstElement = strs.slice(1, strs.length);
  6. if(strs.length===0)return '';
  7. if(strs.length===1)return strs[0];
  8.  
  9. while(index <= firstWord.length) {
  10. if(arrWithoutFirstElement.every(element =>
  11. element.substring(0,index)===firstWord.substring(0,index))){
  12. arrResults.push(firstWord.substring(0,index));
  13. }
  14. index++;
  15. }
  16.  
  17. return arrResults.length > 0 ? arrResults[arrResults.length-1] : '';
  18. }
  19.  
  20. console.log(longestCommonPrefix(["flower","flow","flight"]));
Add Comment
Please, Sign In to add comment