JavaScript 透過物件屬性統計物件陣列中唯一元素的數量?


假設,我們有一個包含有關在餐館下單資料的物件陣列 −

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 }

更新於:23-11-2020

720 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告