본문 바로가기

공부/입문자를 위한 Javascript 알고리즘 이론+실습

[section-05] array (indexOf, splice, slice - 벌레 퇴치)

[인프런x코드캠프] 입문자를 위한 Javascript 알고리즘 이론+실습 강의를 들으며 풀어본 문제들

(출처는 아래 링크)

 

[인프런x코드캠프] 입문자를 위한 Javascript 알고리즘 이론+실습

 

function solution(feature) {
  // 1. 배열의 버그의 위치 찾기
  const bug_index = feature.indexOf("bug");
  // 버그가 없을 경우는 기존 배열 return
  if (bug_index === -1) {
    return feature;
  }

  // 2. 그 버그를 제거한 배열 구하기
  // 2-1) splice 사용
  // feature.splice(bug_index, 1);
  // return feature;

  // 2-2) Slice 사용
  // 버그의 인덱스 전까지의 요소들
  const arr1 = feature.slice(0, bug_index);
  // 버그의 인덱스 이후부터 끝까지의 요소들
  const arr2 = feature.slice(bug_index + 1);

  // return arr1.concat(arr2);
  return [...arr1, ...arr2];
}

solution(["code", "bug", "code"]); // ["code", "code"]
solution(["code", "code"]); // ["code", "code"]