CodeWars 코딩 문제 2021/04/21 - Which are in?

이호현·2021년 4월 21일
0

Algorithm

목록 보기
106/138

[문제]

Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2.

#Example 1: a1 = ["arp", "live", "strong"]

a2 = ["lively", "alive", "harp", "sharp", "armstrong"]

returns ["arp", "live", "strong"]

#Example 2: a1 = ["tarp", "mice", "bull"]

a2 = ["lively", "alive", "harp", "sharp", "armstrong"]

returns []

Notes:

  • Arrays are written in "general" notation. See "Your Test Cases" for examples in your language.

  • In Shell bash a1 and a2 are strings. The return is a string where words are separated by commas.

  • Beware: r must be without duplicates.
    Don't mutate the inputs.

(요약) 첫 번째 배열 요소 중에서 두 번째 배열의 아무 문자열에 속해 있으면 그것들만 모아서 return.

[풀이]

function inArray(array1,array2){
  return array1.filter(str1 => {
    for(let i = 0; i < array2.length; i++) {
      if(array2[i].includes(str1)) {
        return true;
      }
    }
  }).sort();
}

array1에서 요소를 뽑아야하니 array1filter로 걸러냄.

array2를 돌면서 각 요소중 array1이 속한 문자열이 있으면 바로 truereturn해서 그 요소만 남김.

마지막에 sort로 정렬해서 return.

profile
평생 개발자로 살고싶습니다

0개의 댓글