ใช้ map() ร่วมกับ Ternary Operator เลือก Object ที่มีค่า Property มากกว่า
ตัวอย่างโค้ด
let firstCustomerDetails = [
{firstName: 'John', amount: 100},
{firstName: 'David', amount: 50},
{firstName: 'Bob', amount: 80}
];
let secondCustomerDetails = [
{firstName: 'John', amount: 400},
{firstName: 'David', amount: 70},
{firstName: 'Bob', amount: 40}
];
var output = firstCustomerDetails.map((key, position) =>
key.amount > secondCustomerDetails[position].amount ? key : secondCustomerDetails[position]
);
console.log(output);
วิธีรันโปรแกรม
ใช้คำสั่ง node fileName.js (เช่น node demo83.js)
ผลลัพธ์
[
{ firstName: 'John', amount: 400 },
{ firstName: 'David', amount: 70 },
{ firstName: 'Bob', amount: 80 }
]