I have DataArray1 and DataArray2 , by comparing both i try to create new array without affect existing one (DataArray1)
DataArray1 = [
{
id :'1",
name : "sachin",
age: "23",
addre :"xyz",
amount: '78',
},
{
id :'2",
name : "rahul",
age: "12",
addre :"xyz",
amount: '23',
},
{
id :'3",
name : "messi",
age: "34",
addre :"xyz",
amount: '230',
},
{
id :'4",
name : "vinay",
age: "16",
addre :"xyz",
amount: '67',
}
DataArray2 = [
{
id :'4",
mobile : "12121"
},
{
id :'1",
mobile : "3434"
}
comparing id of the both array and changed amount and pushed into new array without affecting exisintg DataArray1
if(DataArray1 && DataArray1?.length > 0 && DataArray2 && DataArray2?.length > 0) {
newData = DataArray1.forEach(item => {
const matchingData = DataArray2.find(
siteDataObj => item.id === siteDataObj.id
);
if (matchingData) {
item.amount = 0;
} else {
item.amount = 100;
}
});
}
setNewdata(newData);
But in this code existing DataArray1 still affecting with new amount value.
Expected result :
result = [
{
id :'1",
name : "sachin",
age: "23",
addre :"xyz",
amount: '100',
},
{
id :'2",
name : "rahul",
age: "12",
addre :"xyz",
amount: '0',
},
{
id :'3",
name : "messi",
age: "34",
addre :"xyz",
amount: '0',
},
{
id :'4",
name : "vinay",
age: "16",
addre :"xyz",
amount: '100',
}
4
Answers
If I understand correctly, you want to check if there are any items in DataArray1 that are equal to any corresponding items in another array. If there’s a match, the amount should be set to 100; otherwise, it should be set to 0. If that’s the case, you could begin by extracting all keys from the second list and putting them into a new list:
then using map achieve a new list of item:
on map we loop through all item in the first array and check whether we have such id into the second one or not, if we have, we return a new object and adjust the amount.
the problem with your code snippet is you are mutating your object inside the array.
You can map array 1 and array 2 as you did in forEach. Then, return newly created elements without changing the array1 or array2 elements. Use …(Spread syntax) to get all fields in the object and then set the amount manually according to the
matchingData
Hope, it’s clear and helpful
You are directly modifying the values in DataArray1. When you iterate over each item in DataArray1 and then are setting the item to 0 or 100 when you call
Also, foreach does not return a new array. It just modifies the existing. If you just want to return a new array, you can use .map(). Instead of setting item.amount, you could copy the item and return a modified copy of the item. Something like this:
Just to note, in your expected result, you say you are expecting the entries with id 1 and 4 to have amount of 100. But in your code, if you find a match you set the amount to 0. So either the expected result is wrong, or you need to switch your code and set the amount to 100 if you find a match.