Longest String Consisting of N Consecutive Strings in JavaScript



Problem

We are required to write a JavaScript function that takes in an array of strings. Our function should create combinations by combining all possible n consecutive strings in the array and return the longest such string that comes first.

Example

Following is the code −

 Live Demo

const arr = ["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"];
const num = 2;
function longestConsec(strarr, k) {
   if (strarr.length == 0 || k > strarr.length || k <= 0) return '';
      let longStr = '';
   let newStr = '';
   for (let i = 0; i < strarr.length; i++){
      newStr = strarr.slice(i, i+k);
      if (newStr.join('').length > longStr.length ){
         longStr = newStr.join('');
      }
   }
   return longStr;
}
console.log(longestConsec(arr, num));

Output

abigailtheta
Updated on: 2021-04-17T12:46:12+05:30

365 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements