สมมติว่ามีอาร์เรย์ของออบเจ็กต์ต่อไปนี้ที่มีข้อมูลเกี่ยวกับออเดอร์ที่สั่งในร้านอาหาร:
const orders = [
{table_id: 3, food_id: 5},
{table_id: 4, food_id: 2},
{table_id: 1, food_id: 6},
{table_id: 3, food_id: 4},
{table_id: 4, food_id: 6},
];
เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าว ฟังก์ชันควรนับจำนวนคุณสมบัติ table_id ที่ไม่ซ้ำกันในอาร์เรย์ (คือจำนวนโต๊ะที่ไม่ซ้ำกันที่มีการจองออเดอร์)
และจำนวนคุณสมบัติ food_id ที่ไม่ซ้ำกัน (คือจำนวนเมนูอาหารที่ไม่ซ้ำกันที่ถูกสั่ง)
ตัวอย่าง
const orders = [
{table_id: 3, food_id: 5},
{table_id: 4, food_id: 2},
{table_id: 1, food_id: 6},
{table_id: 3, food_id: 4},
{table_id: 4, food_id: 6},
];
const countUniques = (orders = []) => {
const tableObj = {}, foodObj = {};
orders.forEach(el => {
tableObj[el.table_id] = null;
foodObj[el.food_id] = null;
});
const tableUniqueIDs = Object.keys(tableObj).length;
const foodUniqueIDs = Object.keys(foodObj).length;
return {
tableUniqueIDs, foodUniqueIDs
};
};
console.log(countUniques(orders));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้:
{ tableUniqueIDs: 3, foodUniqueIDs: 4 }