i have two array of objects like below, am trying to compare two arrays and looking to update the object total value of arr1 if the id matches with arr2.
const arr1 = [
{
id: 1,
value: { total: 0 },
},
{
id: 2,
value: { total: 0 },
},
{
id: 3,
value: { total: 0 },
},
id: 4,
value: { total: 0 },
},
];
const arr2 = [
{
id: 2,
value: 3 ,
},
{
id: 3,
value: 5,
},
];
I am trying to compare two arrays and looking to update the object total value of arr1 if the id matches with arr2
expected result is
const arr1 = [
{
id: 1,
value: { total: 0 },
},
{
id: 2,
value: { total: 3 },
},
{
id: 3,
value: { total: 5 },
},
{
id: 4,
value: { total: 0 },
},
];
I have tried the below code,
arr1.map((item) => {
arr2.find((element) => {
if (element.id === item.id ) {
item = {
...item,
value: {
...item.value,
total: item.value.total element.value,
},
};
console.log(item);
}
});
return item;
});
CodePudding user response:
I have changed the find function to the filter function and will add the result to the original array.
try this
const arr1 = [
{
id: 1,
value: { total: 0 },
},
{
id: 2,
value: { total: 0 },
},
{
id: 3,
value: { total: 0 },
},
{
id: 4,
value: { total: 0 },
}
]
const arr2 = [
{
id: 2,
value: 3 ,
},
{
id: 3,
value: 5,
},
];
arr1.map((item) => {
let result = arr2.filter((element) => element.id == item.id)
if(result && result.length) {
item.value.total = result[0].value
}
return item;
});
console.log(arr1)
CodePudding user response:
You have to assign map to your array:
this.arr1 = this.arr1.map((item) => {
this.arr2.find((element) => {
if (element.id === item.id) {
item = {
...item,
value: {
...item.value,
total: item.value.total element.value,
},
};
console.log(item);
}
});
return item;
});
CodePudding user response:
If each object's id
is unique (within each array), you can do:
arr1.forEach((obj1) => {
const obj2Match = arr2.find((obj2) => obj1.id === obj2.id );
if (obj2Match) {
obj1.value.total = obj2Match.value;
}
});
If more than one object can have the same id
(e.g. arr2
has two objects that have the id
of 2), then you can do:
arr1.forEach((obj1) => {
const obj2Matches = arr2.filter((obj2) => obj1.id === obj2.id );
if (obj2Matches.length) {
obj1.value.total = obj2Matches.reduce(((accum, curr) => accum curr.value), 0);
}
});
Complexity:
- Time: O(N * M)
- Space: O(M)
- N => arr1.length, M => arr2.length
CodePudding user response:
You could do something like this:
arr2.map((x) => {
let result = arr1.filter((a1) => a1.id === x.id);
if (result.length > 0) {
x.total = result[0].total;
}
return x;
});