과거 프로그래밍 자료들/코딩테스트
자바스크립트 문제 - 2
평부
2022. 6. 16. 21:41
* 출처 : https://learnjs.vlpt.us/basics/09-array-functions.html
[문제]
숫자 배열이 주어졌을 때 10보다 큰 숫자의 갯수를 반환하는 함수를 만드세요
1
2
3
4
5
6
|
function countBiggerThanTen(numbers) {
/* 구현해보세요 */
}
const count = countBiggerThanTen([1, 2, 3, 5, 10, 20, 30, 40, 50, 60]);
console.log(count); // 5
|
cs |
[해결]
1. forEach
1
2
3
4
5
6
7
8
9
10
11
12
|
function countBiggerThanTen(numbers) {
let count = 0;
numbers.forEach(n => {
if(n > 10) {
count++;
}
})
return count;
}
const count = countBiggerThanTen([1, 2, 3, 5, 10, 20, 30, 40, 50, 60]);
console.log(count); // 5
|
cs |
2. filter
1
2
3
4
5
6
7
8
|
function countBiggerThanTen(numbers) {
return numbers.filter(n => n > 10).length;
}
const count = countBiggerThanTen([1, 2, 3, 5, 10, 20, 30, 40, 50, 60]);
console.log(count); // 5
|
cs |
3. reduce
1
2
3
4
5
6
7
8
9
10
11
12
13
|
function countBiggerThanTen(numbers) {
return numbers.reduce((a, b) => {
if (b > 10) {
return a + 1;
} else {
return a;
}
}, 0);
}
const count = countBiggerThanTen([1, 2, 3, 5, 10, 20, 30, 40, 50, 60]);
console.log(count); // 5
|
cs |