Home > Net >  How to set state array by merging it with another array without having duplicates?
How to set state array by merging it with another array without having duplicates?

Time:12-05

How to properly add objects from another array to my state array without having the same element twice?

The state array:

const [arr, setArr] = useState([1,2,3])

The array I want to merge the state array with:

const someArr = [2,3,4,5]

The wanted outcome is arr = [1,2,3,4,5]

Doing something like:

const arr3 = [...new Set([...arr, ...someArr])]
setArr(arr3)

works, but I'm sure that's the wrong solution for this. Thanks!

CodePudding user response:

To properly add the objects from someArr to the state array without having the same element twice, you can use the Set data structure to store the elements of the state array, and then use the spread operator and the concat method to add the elements of someArr to the Set without duplicates. Finally, you can convert the Set back to an array and set it as the new state.

Here's an example of how you can do this:

const [arr, setArr] = useState([1,2,3]);
const someArr = [2,3,4,5];

// Create a Set from the state array
const set = new Set(arr);

// Add the elements of someArr to the Set without duplicates
set.add(...someArr);

// Convert the Set back to an array and set it as the new state
setArr([...set]);

// arr is now [1,2,3,4,5]

Alternatively, you can use the filter method to remove duplicates from the someArr array before adding it to the state array.

Here's an example of how you can do this:

const [arr, setArr] = useState([1,2,3]);
const someArr = [2,3,4,5];

// Remove duplicates from someArr using the filter method
const filteredArr = someArr.filter(x => !arr.includes(x));

// Add the elements of filteredArr to the state array
setArr(arr.concat(filteredArr));

// arr is now [1,2,3,4,5]

In both examples, the state array arr will be updated to contain the elements from someArr without duplicates. The Set data structure is more efficient for checking for duplicates, but using the filter method is more straightforward and may be easier to understand. You can choose the approach that works best for your use case.

  • Related