skip to Main Content

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


  1. 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:

    const DataArray2Keys = DataArray2.map(d => d.id);
    

    then using map achieve a new list of item:

    const updatedArr = DataArray1.map((d) => DataArray2Keys.includes(d.id) ? ({...d, amount: 100}) : ({...d, amount: 0}))
    

    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.

    Login or Signup to reply.
  2. 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

    const 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',
    }];
    
    const DataArray2 = [
    {
     id :"4",
     mobile : "12121" 
    },
    {
     id :"1",
    mobile : "3434" 
    }];
    
    const newData = DataArray1.map(item => {
        const matchingData = DataArray2.some(
            siteDataObj => item.id === siteDataObj.id
        );
                  
        return {
            ...item,
            amount: matchingData ? 100 : 0
        };
    }); 
    
    // setNewdata(newData);
    
    console.log("Output:", newData);
    console.log("DataArray1:", DataArray1);

    Hope, it’s clear and helpful

    Login or Signup to reply.
  3. const 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',
    }
    ]
    
    
    const DataArray2 = [
    {
    id :"4",
    mobile : "12121" 
    },
    {
    id :"1",
    mobile : "3434" 
    }
    ]
    
    const newData = JSON.parse(JSON.stringify(DataArray1));
    
    const setNewData = () => {
     if(DataArray1 && DataArray1?.length > 0 && DataArray2 && DataArray2?.length > 0) {
        DataArray1.forEach((item, index) => {
         const matchingData = DataArray2.find(
                   siteDataObj => item.id === siteDataObj.id
                 )
           if (matchingData) {
             newData[index].amount = '0'; 
           } else {
             newData[index].amount = '100'; 
           }
         });
         }
    }
    setNewData();
    
    console.log("DataArray1", DataArray1);
    console.log("newData", newData);
    Login or Signup to reply.
  4. 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

    item.amount = 
    

    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:

    const newData = DataArray1.map(item => {
       const matchingData = DataArray2.find(siteDataObj => item.id === siteDataObj.id);
       let newAmount;
       if(matchingData) {
         newAmount = 0;
       } else {
         newAmount = 100;
       }
       return {...item, amount: newAmount} <-- The ... is a spread operator and it copies the object. 
    });
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search