Home > OS >  Add items to an array without duplicates with using Map object
Add items to an array without duplicates with using Map object

Time:08-02

I'm trying to add new values to an array without duplicates.

I'm using Map object to hold the previous array and trying to filter the new array

const [items, setItems] = useState([]);

    const res = () => {
        const map1 = new Map(
            arr.map(obj => {
                return [obj.id, obj];
            })
        );

        setItems([map1, ...data.result.filter(x => x.id !== map1.forEach((val, key) => key))]);
    };

How to accomplish this iteration successfully? Are there other ways with using Map object that would be better in this case?

CodePudding user response:

How to accomplish this iteration successfully?

To test map membership you should not iterate the map. The advantage of a map is that you can check for membership with has. Also, you should not include the map as the first element of the new array, but spread the original arr (or the values of the map):

setItems([...arr, ...data.result.filter(x => !map1.has(x.id)]);

Are there other ways with using Map object that would be better in this case?

You could first join the new data to the array and then extract the unique values from it via a Map:

const res = () => {
    const map1 = new Map(
        data.result.concat(arr).map(obj => {
            return [obj.id, obj];
        })
    );

    setItems([...map1.values()]);
};

Note that data.result is put in front of arr so to ensure that the existing value has precedence when there is a duplicate. If you prefer that the new value would need to overwrite the previous value for the same id, then reverse that order. If you want the old value to remain, and you want the really new elements to occur at the end of the array, then do:

        arr.concat(data.result, arr).map(obj => {
            // ...etc
  • Related