Can all array elements mesh together in JavaScript?



Problem

Two words can mesh together if the ending substring of the first is the starting substring of the second. For instance, robinhood and hoodie can mesh together.

We are required to write a JavaScript function that takes in an array of strings. If all the words in the given array mesh together, then our function should return the meshed letters in a string, otherwise we should return an empty string.

Example

Following is the code −

 Live Demo

const arr = ["allow", "lowering", "ringmaster", "terror"];
const meshArray = (arr = []) => {
   let res = "";
   for(let i = 0; i < arr.length-1; i++){
      let temp = (arr[i] + " " + arr[i + 1]).match(/(.+) \1/);
      if(!temp){
         return '';
      };
      res += temp[1];
   };
   return res;
};
console.log(meshArray(arr));

Output

Following is the console output −

lowringter

Advertisements