สมมติว่ามีอาร์เรย์ที่เก็บข้อมูลหุ้นที่ซื้อและขายของบริษัทในช่วงเวลาหนึ่ง
const transactions = [ ['AAPL', 'buy', 100], ['WMT', 'sell', 75], ['MCD', 'buy', 125], ['GOOG', 'sell', 10], ['AAPL', 'buy', 100], ['AAPL', 'sell', 100], ['AAPL', 'sell', 20], ['DIS', 'buy', 15], ['MCD', 'buy', 10], ['WMT', 'buy', 50], ['MCD', 'sell', 90] ];
เราต้องการเขียนฟังก์ชันที่รับข้อมูลนี้และคืนค่าออบเจกต์ของอาร์เรย์ โดยคีย์เป็นชื่อหุ้น (เช่น 'AAPL', 'MCD') และค่าเป็นอาร์เรย์สองตัวเลข โดยตัวแทนแสดงยอดซื้อรวม และตัวที่สองแสดงยอดขายรวม โค้ดสำหรับทำเช่นนี้คือ
ตัวอย่าง
const transactions = [ ['AAPL', 'buy', 100], ['WMT', 'sell', 75], ['MCD', 'buy', 125], ['GOOG', 'sell', 10], ['AAPL', 'buy', 100], ['AAPL', 'sell', 100], ['AAPL', 'sell', 20], ['DIS', 'buy', 15], ['MCD', 'buy', 10], ['WMT', 'buy', 50], ['MCD', 'sell', 90] ]; const digestTransactions = (arr) => { return arr.reduce((acc, val, ind) => { const [stock, type, amount] = val; if(acc[stock]){ const [buy, sell] = acc[stock]; if(type === 'buy'){ acc[stock] = [buy+amount, sell]; }else{ acc[stock] = [buy, sell+amount]; } }else{ if(type === 'buy'){ acc[stock] = [amount, 0]; }else{ acc[stock] = [0, amount]; } } return acc; }, {}); }; console.log(digestTransactions(transactions));ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
{ AAPL: [ 200, 120 ], WMT: [ 50, 75 ], MCD: [ 135, 90 ], GOOG: [ 0, 10 ], DIS: [ 15, 0 ] }