สมมุติว่า เรามีสองสิ่งนี้ −
const obj1 = {
positive: ['happy', 'excited', 'joyful'],
negative: ['depressed', 'sad', 'unhappy']
};
const obj2 = {
happy: 6,
excited: 1,
unhappy: 3
}; เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับในสองอ็อบเจ็กต์ดังกล่าว ฟังก์ชันควรใช้วัตถุทั้งสองนี้ในการคำนวณคะแนนบวกและลบ และส่งคืนวัตถุเช่นนี้ −
const output = {positive: 7, negative: 3}; ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
const obj1 = {
positive: ['happy', 'excited', 'joyful'],
negative: ['depressed', 'sad', 'unhappy']
};
const obj2 = {
happy: 6,
excited: 1,
unhappy: 3
};
const findPositiveNegative = (obj1 = {}, obj2 = {}) => {
const result ={}
for (let key of Object.keys(obj1)) {
result[key] = obj1[key].reduce((acc, value) => {
return acc + (obj2[value] || 0);
}, 0)
};
return result;
};
console.log(findPositiveNegative(obj1, obj2)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
{ positive: 7, negative: 3 }