Skip to content

Commit ddb4fbd

Browse files
committed
feat: 数组diff的 Map 解法
1 parent e1edb73 commit ddb4fbd

1 file changed

Lines changed: 65 additions & 1 deletion

File tree

JS/algorithm/pDd/2026春/数组比较.js

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,68 @@ function diffList(oldList, newList, key) {
7272
// 并且题目说层数只需要一层,所以也不用写边界条件去递归DFS
7373

7474

75+
// Map解法
76+
function diffList_2(oldList, newList, key = 'id') {
77+
const ans = {
78+
added: [],
79+
removed: [],
80+
changed: []
81+
}
82+
83+
const oldMap = new Map()
84+
85+
// 1. 旧数组建表
86+
for (const item of oldList) {
87+
oldMap.set(item[key], item)
88+
}
89+
90+
// 2. 遍历新数组,找新增和修改
91+
for (const newItem of newList) {
92+
const id = newItem[key]
93+
const oldItem = oldMap.get(id)
94+
95+
// 新增
96+
if (!oldMap.has(id)) {
97+
ans.added.push(newItem)
98+
continue
99+
}
100+
101+
// 比较字段
102+
const fields = []
103+
const keys = [...new Set([
104+
...Object.keys(oldItem),
105+
...Object.keys(newItem)
106+
])]
107+
108+
for (const k of keys) {
109+
if (oldItem[k] !== newItem[k]) {
110+
fields.push({
111+
field: k,
112+
oldVal: oldItem[k],
113+
newVal: newItem[k]
114+
})
115+
}
116+
}
117+
118+
if (fields.length > 0) {
119+
ans.changed.push({
120+
[key]: id,
121+
fields
122+
})
123+
}
124+
125+
// 处理完就删掉,剩下的就是 removed
126+
oldMap.delete(id)
127+
}
128+
129+
// 3. oldMap 里剩下的是删除项
130+
for (const item of oldMap.values()) {
131+
ans.removed.push(item)
132+
}
133+
134+
return ans
135+
}
136+
75137
const oldList = [
76138
{ id: 1, name: 'ceilf6', price: 100 },
77139
{ id: 3, name: 'ceilf7', price: 100 },
@@ -84,4 +146,6 @@ const newList = [
84146
{ id: 4, name: 'ceilf8', price: 200 },
85147
{ id: 6, name: 'ceilf10', price: 200 }
86148
]
87-
console.log(diffList(oldList, newList, 'id'))
149+
console.log(diffList(oldList, newList, 'id'))
150+
console.log('===')
151+
console.log(diffList_2(oldList, newList, 'id'))

0 commit comments

Comments
 (0)