removeEveryOther.js (8kyu 33)

Codewars 알고리즘 풀이


Description

  • 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(['1', '2', '3', '4']);  // ['1', '3']
removeEveryOther([[1], [2]]);            // [[1]]
removeEveryOther([[1, 2]]);              // [[1, 2]]


Solution 02

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(['1', '2', '3', '4']);  // ['1', '3']
removeEveryOther([[1], [2]]);            // [[1]]
removeEveryOther([[1, 2]]);              // [[1, 2]]


Solution 03

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

removeEveryOther([1, 2, 3, 4]);          // [1, 3]
removeEveryOther(['1', '2', '3', '4']);  // ['1', '3']
removeEveryOther([[1], [2]]);            // [[1]]
removeEveryOther([[1, 2]]);              // [[1, 2]]


Solution 04

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

removeEveryOther([1, 2, 3, 4]);          // [1, 3]
removeEveryOther(['1', '2', '3', '4']);  // ['1', '3']
removeEveryOther([[1], [2]]);            // [[1]]
removeEveryOther([[1, 2]]);              // [[1, 2]]