我有兩個物件陣列,arr1并arr2假設兩者的長度相等。兩者都有{id: 'some random id', ...}內部結構。我想遍歷每個物件arr1并添加一個引數,checked=false如果id該物件不屬于arr2else 添加一個checked=true.
這是我目前的代碼:
for (const i of arr1) {
i.checked = false;
for (const j of arr2) {
if (i.id === j.id) {
i.checked = true;
}
}
}
我如何優化它?任何小于 O(n^2) 的建議表示贊賞。
uj5u.com熱心網友回復:
您可以創建一個 Set,它們具有 O(1) 訪問權限,使您的回圈 O(n)
const idSet = new Set(arr2.map(i => i.id))
for (const i of arr1) {
i.checked = idSet.has(i.id);
}
uj5u.com熱心網友回復:
您可以使用Set從第二個陣列中準備 ID,然后使用Set.prototype.has其中的 O(1) 操作。
const arr1 = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]
const arr2 = [{id: 2}, {id: 5}, {id: 4}, {id: 6}]
const ids = new Set(arr2.map(({ id }) => id))
for (const item of arr1) {
item.checked = ids.has(item.id)
}
console.log(arr1)
/* Result
[
{ id: 1, checked: false },
{ id: 2, checked: true },
{ id: 3, checked: false },
{ id: 4, checked: true }
]
*/
快速基準:
Running "Array check (1000 elements)" suite...
Progress: 100%
Set.has:
15 671 ops/s, ±0.38% | fastest
two loops:
543 ops/s, ±0.48% | slowest, 96.54% slower
Finished 2 cases!
Fastest: Set.has
Slowest: two loops
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/334774.html
標籤:javascript 有角的 打字稿 算法 离子框架
