본문 바로가기
알고리즘/Codewars

[Codewars] Removing Elements (8 kyu) / JavaScript

by fluss 2022. 11. 12.

https://www.codewars.com/kata/5769b3802ae6f8e4890009d2

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Take an array and remove every second element from the array. Always keep the first element and start removing with the next element.

 

Example:

["Keep", "Remove", "Keep", "Remove", "Keep", ...] --> ["Keep", "Keep", "Keep", ...]

None of the arrays will be empty, so you don't have to worry about that!

 


 

설명:

배열을 받아 배열의 모든 두 번째 요소를 제거하세요. 항상 첫 번째 요소를 유지하고 다음 요소를 제거해야 합니다.

 

예시:

["Keep", "Remove", "Keep", "Remove", "Keep", ...] --> ["Keep", "Keep", "Keep", ...]

어떤 배열도 비어있지 않으니 그것에 대해 걱정하지 마세요!

 

풀이

i가 0일 때부터 반복문을 돌려 i가 짝수일 때 그 위치에 있는 배열의 요소를 결과 배열에 담아 출력하였다. 

 

코드

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

댓글