
정수 배열 arr과 delete_list가 있습니다. arr의 원소 중 delete_list의 원소를 모두 삭제하고 남은 원소들은 기존의 arr에 있던 순서를 유지한 배열을 return 하는 solution 함수를 작성해 주세요.
arr의 길이 ≤ 100arr의 원소 ≤ 1,000arr의 원소는 모두 서로 다릅니다.delete_list의 길이 ≤ 100delete_list의 원소 ≤ 1,000delete_list의 원소는 모두 서로 다릅니다.//👀 나의 코드
function solution(arr, delete_list) {
for(const i of delete_list){
const idx = [...arr].findIndex((el) => el === i)
if(idx > 0) arr.splice(idx, 1)
}
return arr;
}
👉🏻 코드 실행은 통과했지만, 제출후 채점하기에서 실패케이스가 나왔다.
실패하는 케이스를 찾아서 추가해보았다.
👉🏻 [654]가 삭제되지 않는 현상을 발견하고, 코드를 보니 if문의 조건이 잘못되어 있음을 알았다.
function solution(arr, delete_list) {
for(const i of delete_list){
const idx = [...arr].findIndex((el) => el === i)
if(idx >= 0) arr.splice(idx, 1)
}
return arr;
}
👉🏻 findIndex 는 false일 경우 -1을 리턴하므로, if문 작성시 (idx > -1) 혹은 (idx >= 0) 로 작성해야 한다.