Description
- Given an array of integers.
- Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers.
- 첫 번째 element는 양수의 개수, 두 번째 element는 음수의 합인 배열을 반환한다.
- If the input array is empty or null, return an empty array.
- 입력 배열이 비어 있거나 null인 경우 빈 배열을 반환한다.
Solution 01
function countPositivesSumNegatives(arr) {
if (arr === null || arr.length === 0) return [];
let count = 0;
let sum = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > 0) count+=;
if (arr[i] < 0) sum += arr[i];
}
return [count, sum];
}
countPositivesSumNegatives([]); // []
countPositivesSumNegatives([1, 2, 3, 4, -11, -13]); // [4, -24]
countPositivesSumNegatives([0, 1, 2, -1, -2]); // [2, -3]
Solution 02
function countPositivesSumNegatives(arr) {
if (!arr || !arr.length) return [];
let count = 0;
let sum = 0;
arr.forEach(i => {
if (i > 0) count++;
if (i < 0) sum += i;
});
return [count, sum];
}
countPositivesSumNegatives([]); // []
countPositivesSumNegatives([1, 2, 3, 4, -11, -13]); // [4, -24]
countPositivesSumNegatives([0, 1, 2, -1, -2]); // [2, -3]
Solution 03
function countPositivesSumNegatives(arr) {
return arr && arr.length ? [arr.filter(i => i > 0).length, arr.filter(i => i < 0).reduce((sum, i) => sum + i, 0)] : [];
}
countPositivesSumNegatives([]); // []
countPositivesSumNegatives([1, 2, 3, 4, -11, -13]); // [4, -24]
countPositivesSumNegatives([0, 1, 2, -1, -2]); // [2, -3]