Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Can all array elements mesh together in JavaScript?
Two words can mesh together if the ending substring of the first word is the starting substring of the second word. For instance, "robinhood" and "hoodie" can mesh together because "hood" appears at the end of "robinhood" and at the start of "hoodie".
We need to write a JavaScript function that takes an array of strings and checks if all consecutive words mesh together. If they do, the function returns the meshed letters as a string, otherwise it returns an empty string.
How It Works
The solution uses a regular expression to find overlapping substrings between consecutive words. The pattern (.+) \1 matches when the end of the first word equals the beginning of the second word.
Example
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));
lowringter
Step-by-Step Breakdown
Let's trace through the example array:
const arr = ["allow", "lowering", "ringmaster", "terror"];
// Step 1: "allow" + " " + "lowering" = "allow lowering"
// Match: "low" (end of "allow" = start of "lowering")
// Step 2: "lowering" + " " + "ringmaster" = "lowering ringmaster"
// Match: "ring" (end of "lowering" = start of "ringmaster")
// Step 3: "ringmaster" + " " + "terror" = "ringmaster terror"
// Match: "ter" (end of "ringmaster" = start of "terror")
// Result: "low" + "ring" + "ter" = "lowringter"
console.log("Step by step:");
console.log("allow ? lowering: 'low'");
console.log("lowering ? ringmaster: 'ring'");
console.log("ringmaster ? terror: 'ter'");
console.log("Final result: 'lowringter'");
Step by step: allow ? lowering: 'low' lowering ? ringmaster: 'ring' ringmaster ? terror: 'ter' Final result: 'lowringter'
Example with No Mesh
const noMeshArr = ["hello", "world", "javascript"];
console.log(meshArray(noMeshArr)); // Returns empty string
console.log("No common substring between 'hello' and 'world'");
No common substring between 'hello' and 'world'
Conclusion
The mesh function uses regular expressions to find overlapping substrings between consecutive array elements. It returns the concatenated mesh parts if all words connect, or an empty string if any pair fails to mesh.
