Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements