1

I want to remove all elements from an array that are in another array. In other words, I want to compare two arrays with each other and remove all elements which are duplicate from an array. So far I have the following program code, but it doesn't work. The elements are not removed

React.useEffect(() => {

const aLeft = right.filter((r) => !left.includes(r));

var array = [...left];  

for (const [index, value] of array.entries()) {

  var item = array.indexOf(value); 

  if (item !== -1) {

    console.log(item);

    array.splice(item, 1);

    setLeft(array);

  }

}

}, []);

EDIT

Still does not work. Regarding the issue: I have a database in which the right side of the picture (assigned trainees) is saved. The left side contains all trainees who are also initially read from the database in a useEffekt method. Now I would like to compare both arrays with each other at runtime and not show all participants from the right side in the left column.

React.useEffect(() => {
 const inters = teilnehmer.filter((x => !azubis.includes(x));

 setLeft(inters );

},[]);

enter image description here

schorle88
  • 103
  • 6
  • See [this answer](https://stackoverflow.com/a/33034768/) - you probably want `right.filter(x => !left.includes(x)).concat(left.filter(x => !right.includes(x)));` – VLAZ Oct 22 '20 at 05:59
  • See also: [this answer](https://stackoverflow.com/a/58626840/) for an approach using sets and set operations. – VLAZ Oct 22 '20 at 06:03

2 Answers2

0

This is a good candidate for useMemo. The resulting array will be cached, only recalculated when left or right changes.

const intersection = useMemo(() => {
  const uniqueLeft = left.filter(item => !right.includes(item));
  const uniqueRight = right.filter(item => !left.includes(item));

  return [...uniqueLeft, ...uniqueRight];
}, [left, right]);
David L. Walsh
  • 24,097
  • 10
  • 61
  • 46
0

const arr = [1,2,4,1]

Array.from(new Set(arr))

Output :- [1, 2, 4]