Description
- Take an array and remove every second element out of that array.
- 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]]