
정수 배열 arr가 주어집니다. 배열 안의 2가 모두 포함된 가장 작은 연속된 부분 배열을 return 하는 solution 함수를 완성해 주세요.
단, arr에 2가 없는 경우 [-1]을 return 합니다.
function solution(a, b, c) {
var answer = 0;
return answer;
}
function solution(arr) {
let answer = [];
if (arr.includes(2)) {
arr.map((item, index) => (item === 2 ? answer.push(index) : null));
return arr.splice(answer[0], answer[answer.length - 1]);
} else {
return [-1];
}
}
solution([1, 2, 1, 2, 1, 10, 2, 1]);
map을 활용해서 item이 숫자 2와 같다면, 해당 item의 index를 answer에 넣어준다.answer의 0번째에 들어있는 index와 answer의 전체 길이에서 1을 빼준 위치의 숫자까지 반환해 준다.index는 0부터 시작하지만 length는 1부터 시작하니까 1을 빼줘야 마지막 index의 값을 뽑아낼 수 있다.)2를 포함하지 않고있다면 [-1]을 반환한다.
🙅♀️ 위 답안은 틀렸다! splice를 사용했기 때문이다.
splice(제거 시작 인덱스, 제거할 갯수)를 의미한다.
solution([2,1,1,4,5,2,9]);
그래서 만약 위와 같은 예제가 들어오게 된다면 오류가 난다.
1. answer에 [1, 3, 6]이 담겼다.
2. answer의 0번째 1과 마지막 6을 splice해준다.
3. 결과값 : [2, 1, 1, 4, 5] -> 오답
function solution(arr) {
let answer = [];
if (arr.includes(2)) {
arr.map((item, index) => (item === 2 ? answer.push(index) : null));
console.log(arr.slice(answer[0], answer[answer.length - 1] + 1));
return arr.slice(answer[0], answer[answer.length - 1] + 1);
} else {
return [-1];
}
}
모든 코드가 동일하지만 splice를 slice로 변경했다.
slice(자를 시작 index, 잘라낼 마지막 index)
❗️잘라낼 마지막 index는 포함되지 않으니 보통 + 1을 해주어야한다.
split, splice, slice 세 메서드 다 철자가 비슷해서 너무 헷갈린다!!
