removeEveryOther.js (8kyu 56)

Codewars 알고리즘 풀이


Problem

  • Take an array and remove every second element out of that array.
    • 배열의 element를 하나 걸러 제거한다.
  • Always keep the first element and start removing with the next element.
    • 항상 첫 번째 element는 유지하고, 그 다음 element부터 제거한다.


Solution 01

function removeEveryOther(arr) {
  let result = [];
  
  for (let i = 0; i < arr.length; i+=2) {
    result.push(arr[i]);
  }
  return result;
}

removeEveryOther([1, 2, 3, 4]);          // [1, 3]
removeEveryOther(['a', 'b', 'c', 'd']);  // ['a', 'c']

push() 메소드

배열의 끝에 새 element를 추가하고, 새로운 길이를 반환한다.


Solution 02

function removeEveryOther(arr) {
  return arr.filter((i, index) => index % 2 === 0);
}

removeEveryOther([1, 2, 3, 4]);          // [1, 3]
removeEveryOther(['a', 'b', 'c', 'd']);  // ['a', 'c']

filter() 메소드

테스트를 통과한 배열의 각 값을 모아, 새 배열로 반환한다.


Solution 03

function removeEveryOther(arr) {
  for (let i = 1; i < arr.length; i++) {
    arr.splice(i, 1);
  }
  return arr;
}

removeEveryOther([1, 2, 3, 4]);          // [1, 3]
removeEveryOther(['a', 'b', 'c', 'd']);  // ['a', 'c']

splice() 메소드

배열에 item을 추가/제거하고, 제거된 item을 반환한다.