Home > database >  Filter out array of object from array of object
Filter out array of object from array of object

Time:09-26

I have the following data

const[myData,setMyData]=React.useState([])
React.useEffect(()=>{
 let initialData=[{ email: '[email protected]', date: '22-03-2020' },
   { email: '[email protected]', date: '22-03-2021' },
   { email: '[email protected]', date: '22-03-2021' }]
 setMyData(initialData)
},[])

this data are displayed in a table with a checkbox and I have this function called everytime I push a button (after having the rows selected)

function add(datatoRemove ){
  alert("datatoRemove " JSON.stringify(datatoRemove ) )
  let myArrayFiltered = myData.filter((el) => {
    return datatoRemove .some((f) => {
      return f.email!== el.email
    });
  });
  alert("filtered" JSON.stringify(myArrayFiltered ) )

  setMyData( [...myArrayFiltered ])    
}

The issue is that with one selection the "myArrayFiltered " returns the other 2 rows and the state is updated correctly but if I select two or all the row nothing changed and the myArrayFiltered have all 3 elements. What am I missing here?

the final goal is:

possible scenario 1: if

datatoRemove = [{ email: '[email protected]', date: '22-03-2020' },
       { email: '[email protected]', date: '22-03-2021' },
       { email: '[email protected]', date: '22-03-2021' }]

then

myArrayFiltered=[] and also the myData= []

possible scenario 2:

if datatoRemove = [ { email: '[email protected]', date: '22-03-2021' },{ 
email: '[email protected]', date: '22-03-2021' }]

then

myArrayFiltered= [{ email: '[email protected]', date: '22-03-2020' }]

and also myData.

CodePudding user response:

You need to use this instead

let myArrayFiltered = initialData.filter((el) => {
  return datatoRemove.every((f) => {
    return f.email!= el.email
  });
});
  • Related