สมมติว่ามีอาร์เรย์ของออบเจ็กต์ดังนี้:
const arr = [
{"goods": "Wheat ", "from": "GHANA", "to": "AUSTRALIA"},
{"goods": "Wheat", "from": "USA", "to": "INDIA"},
{"goods": "Wheat", "from": "SINGAPORE", "to": "MALAYSIA"},
{"goods": "Wheat", "from": "USA", "to": "INDIA"},
];
เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าว เป้าหมายคือคืนค่าอาร์เรย์ของออบเจ็กต์ทั้งหมดจากอาร์เรย์ต้นฉบับที่มีค่า "USA" สำหรับคุณสมบัติ "from" และค่า "INDIA" สำหรับคุณสมบัติ "to"
ตัวอย่าง
const arr = [
{"goods": "Wheat ", "from": "GHANA", "to": "AUSTRALIA"},
{"goods": "Wheat", "from": "USA", "to": "INDIA"},
{"goods": "Wheat", "from": "SINGAPORE", "to": "MALAYSIA"},
{"goods": "Wheat", "from": "USA", "to": "INDIA"},
];
const findDesiredLength = (arr = [], from = 'USA', to = 'INDIA') => {
const filtered = arr.filter(el => {
if(el.from === from && el.to === to){
return true;
}
});
const { length: l } = filtered || [];
return l;
};
console.log(findDesiredLength(arr));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้:
2