0

Есть два массива

["Hello. This is line 1 of text.", "and this is another.", "the end", "line 3 here"]


["the end", "matches", "line 3", "and this is anoother."]

Нужно вывести,если есть совпадение где то в строке.

результат должен быть:

 ['line 3 here','the end','and this is another.']

 

10
  • 2
    Почему 'line 3 here'? Опечатка?
    – Alexey Ten
    29 мая 2019 в 7:29
  • @AlexeyTen да, исправил
    – Улан
    29 мая 2019 в 8:04
  • попробуйте библиотеку lodash метод intersection: lodash.com/docs/4.17.11#intersection 29 мая 2019 в 10:28
  • И всё таки... Строка line 3 here имеется в обеих массивах?
    – XelaNimed
    29 мая 2019 в 10:51
  • @XelaNimed нет, только в первой.
    – Улан
    29 мая 2019 в 11:03

2 ответа 2

1

Используйте комбинацию из indexOf и filter:

var arr1 = ["Hello. This is line 1 of text.", "and this is another.", "the end", "line 3 here"],
    arr2 = ["the end", "matches", "line 3 here", "and this is another."],
    intersect = function(arr1, arr2) {
      return arr1.filter(function(n) {
        return arr2.indexOf(n) !== -1;
      });
    };

console.log(intersect(arr1, arr2));

Ссылки по теме

1

Решение на чистом javascript

var first = ["Hello. This is line 1 of text.", "and this is another.", "the end", "line 3 here"];
var second = ["the end", "matches", "line 3", "and this is anoother."]; 

for (var i = 0; i < first.length; i++) { //проходимся по первому масиву
  for (var j = 0; j< second.length; j++) { // ищем соотвествия во втором массиве
    if(first[i] === second[j]){
      console.log(first[i]); // если совпадаем делаем что либо с этим значением
    }
  }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.