Cần viết hàm nhận vào mảng và trả về object với hai thuộc tính positive và negative, mỗi thuộc tính là mảng chứa các phần tử dương/âm tương ứng từ mảng gốc.
Cách làm đơn giản: dùng Array.prototype.reduce() để phân loại phần tử vào object hai mảng.
Ví dụ
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]));
}Kết quả
Đầu ra trong console sẽ là:
{ 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 ] }