I have two array of objects (users and deposits).
const users = [
{
_id: 1,
username: 'tajmirul',
email: '[email protected]',
},
{
_id: 2,
username: 'tajmirul2',
email: '[email protected]',
},
];
const deposits = [
{
_id: 1,
userId: 1,
amount: 250,
},
{
_id: 2,
userId: 1,
amount: 500,
},
];
I want to calculate total deposit for each user and update the users array. like this
// modified users array will look like this
[
{
_id: 1,
username: 'tajmirul'
deposit: 750,
},
{
_id: 2,
username: 'tajmirul2'
deposit: 0,
}
]
I tried this
users.forEach((user, index) => {
deposits.forEach(deposit => {
if (user._id === deposit.userId) {
if (users[index].deposit) {
users[index].deposit += deposit.amount;
} else {
users[index].deposit = deposit.amount;
}
}
});
});
In this case, the time complexity is O(m * n). Is there any way to reduce the time complexity?
users[i]anddeposits[i]always the for the same id?) If so, you only need a singleconst mapped = users.map((user, i) => /* combine user and deposits[i] */).