function findConsecutiveMatches(string, arr){
const searchStringArr = string.split(' '); // ['i', 'cant', 'swim']
let search = [];
arr.forEach((el, idx) => {
if (searchStringArr[0].toLowerCase() != arr[idx].toLowerCase()){
return;
}
search.push(el);
if (idx == arr.length -1){
return;
}
for (let diff = 1; diff <= Math.min(arr.length - idx + 1, searchStringArr.length -1); diff++){
if (searchStringArr[diff].toLowerCase() != arr[idx + diff].toLowerCase()){
return;
}
search.push(arr[idx + diff]);
}
});
if (search.length != searchStringArr.length){
search = [];
}
console.log(search);
return search;
}
const arr0 = ['i', 'cant', 'solve', 'this', 'problem', 'alone'];
const string0 = "I cant";
findConsecutiveMatches(string0, arr0);
// output: ['i', 'cant'];
const arr1 = ['i', 'cant', 'solve', 'this', 'problem', 'alone'];
const string1 = "I cant swim";
findConsecutiveMatches(string1, arr1);
// output: [];
const arr2 = ['i', 'cant', 'solve', 'this', 'problem', 'alone'];
const string2 = "solve this";
findConsecutiveMatches(string2, arr2);
// output: ['solve', 'this'];
const arr3 = ['i', 'cant', 'solve', 'this', 'problem', 'alone'];
const string3 = "solve this question";
findConsecutiveMatches(string3, arr3);
// output: [];
const arr4 = ['i', 'cant', 'solve', 'this', 'problem', 'alone'];
const string4 = "I solve this";
findConsecutiveMatches(string4, arr4);
// output: [];