เราต้องเขียนฟังก์ชันที่รับอาร์เรย์และคืนค่าออบเจกต์ที่มีสองคุณสมบัติคือ positive และ negative ทั้งคู่ควรเป็นอาร์เรย์ที่มีไอเท็มบวกและลบตามลำดับจากอาร์เรย์
เรื่องนี้ตรงไปตรงมา เราจะใช้ 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 ] }