Issue
I have two arrays of objects namely arr1
and arr2
assuming the length of both are equal. Both have {id: 'some random id', ...}
inner structure. I want to iterate through each object in arr1
and add a parameter checked=false
if id
of that object didn't belong to arr2
else add a checked=true
.
Here is my present code:
for (const i of arr1) {
i.checked = false;
for (const j of arr2) {
if (i.id === j.id) {
i.checked = true;
}
}
}
How do I optimize it? Any suggestions lesser than O(n^2) is appreciated.
Solution
You can create a Set, they have O(1) access making your loop O(n)
const idSet = new Set(arr2.map(i => i.id))
for (const i of arr1) {
i.checked = idSet.has(i.id);
}
Answered By - ted
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.