배열을 받아서 양수와 음수라는 두 가지 속성을 가진 객체를 반환하는 함수를 작성해야 합니다. 둘 다 배열의 모든 긍정적인 항목과 부정적인 항목을 각각 포함하는 배열이어야 합니다.
이것은 매우 간단합니다. Array.prototype.reduce() 메서드를 사용하여 원하는 요소를 선택하고 두 배열의 개체에 넣습니다.
예시
const arr = [
[12, -45, 65, 76, -76, 87, -98],
[54, -65, -98, -23, 78, -9, 1, 3],
[87, -98, 3, -2, 123, -877, 22, -5, 23, -67]
];
const splitArray = (arr) => {
return arr.reduce((acc, val) => {
if(val < 0){
acc['negative'].push(val);
} else {
acc['positive'].push(val);
}
return acc;
}, {
positive: [],
negative: []
})
};
for(let i = 0; i < arr.length; i++){
console.log(splitArray(arr[i]));
} 출력
콘솔의 출력은 -
{ positive: [ 12, 65, 76, 87 ], negative: [ -45, -76, -98 ] }
{ positive: [ 54, 78, 1, 3 ], negative: [ -65, -98, -23, -9 ] }
{
positive: [ 87, 3, 123, 22, 23 ],
negative: [ -98, -2, -877, -5, -67 ]
}