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: 17-Apr-2021

279 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements