-
Notifications
You must be signed in to change notification settings - Fork 4
/
1418.Display_Table_of_Food_Orders_in_a_Restaurant.js
54 lines (52 loc) · 1.62 KB
/
1418.Display_Table_of_Food_Orders_in_a_Restaurant.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* @param {string[][]} orders
* @return {string[][]}
*/
var displayTable = function (orders) {
// 1.统计出哪桌点了什么菜
const map = orders.reduce((acc, cur) => {
const [_, tableNumberi, foodItemi] = cur;
acc.set('foodItems', acc.get('foodItems') ? [...new Set([...acc.get('foodItems'), foodItemi])] : [foodItemi])
const table = acc.get(tableNumberi);
if (table) {
acc.set(tableNumberi, Object.assign(table, {
[foodItemi]:
table[foodItemi] ?
++table[foodItemi] : 1
}));
}
else {
acc.set(tableNumberi, {
[foodItemi]: 1
});
}
return acc;
}, new Map())
// 2.补全本桌没有点其他桌点了的菜
const keys = [...map.keys()].filter((key) => key !== 'foodItems');
const foodItems = [...map.get('foodItems')]
keys.forEach((key) => {
foodItems.forEach((food) => {
if (!(food in map.get(key))) {
map.set(key, Object.assign(map.get(key), {
[food]: 0
}));
}
})
})
// 3.按照指定格式输出
const result = [];
foodItems.sort()
result[0] = ["Table", ...foodItems]
keys.sort((a, b) => parseInt(a) - parseInt(b))
while (keys.length > 0) {
const key = keys.shift();
const item = [key];
const foodItemSorted = foodItems.reduce((acc, cur) => {
acc.push(`${map.get(key)[cur]}`)
return acc
}, item)
result.push(foodItemSorted);
}
return result
};