Сценарий ищет самую большую подстроку в массиве строк. Но если строка не начинается с «А», поиск не выполняется. Как реализовать поиск подстрок внутри? ("ABCDE", "XBCDJL") = BCD
var array = ["ABCDEFZ", "ABCDXYZ"],
prefix = array[0],
len = prefix.length;
for (i=1; i<array.length; i++) {
for (j=0, len=Math.min(len,array[j].length); j<len; j++) {
if (prefix[j] != array[i][j]) {
len = j;
prefix = prefix.substr(0, len);
break;
}
}
}



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вы можете попробовать следующее
var array = ["ABCDEFZ", "EBCDXYZ"];
/* In case there is a match, it has to exist in the first string as well.
* So, irrespective of the length of first string,
* we will do our iterations w.r.t. its length */
function findLargestSubstr(arr) {
if (!arr.length) return;
let length = arr[0].length; // length over the first item in array
let val; // value that will be returned
/* looping through the length of first element combinations
* where the first combination will be the complete string and
* the second will be 1 less than the length and then so on */
outer: for (let i = length; i > 0; i--) {
// For every iteration, create the subset of substring that need to be checked
for (let j=0; j <= length - i; j++) {
// Get the substring
let temp = arr[0].substr(j, i);
// Check for the substring for every element in the array
if (arr.every(v => v.includes(temp))) {
/* If the match is found, then
* set the return value to the match and break the loop's */
val = temp;
break outer;
}
}
}
return val;
}
console.info(findLargestSubstr(array));Поскольку temp по определению является подстрокой arr[0], мне любопытно, почему вам нужно проверить это снова с помощью: if (arr.every(v => v.includes(temp)))? Разве не достаточно проверить if (arr[1].includes(temp))?
@Mark Если в массиве было 2 элемента, то да, а если элементов больше, то нет.
@ Иван - Вы имели в виду, если массив пустой? Вы можете просто добавить безопасную проверку if (!arr.length) return; для этого в функции. См. Обновленный ответ на то же самое.
хорошо зацикливайтесь, пока не найдете первое совпадение ....