0

I've been trying to apply the answers from How to remove all duplicates from an array of objects? on this but couldn't find a good way

My current solution: (this is when adding new iconsProps to the array, I'm trying to avoid adding one that already exists, unsuccesfully), I'm leaving the AnnotationIconsProps type as well, to help..

        const idsExistsOnIconProps = iconsProps.some((id) => ids.includes(id.toString()));

        const existingIndex = iconsProps.findIndex(
            (iconProp) =>
                iconProp.coordinates.left === element.offsetLeft &&
                iconProp.coordinates.top === element.offsetTop &&
                !idsExistsOnIconProps
        );

        if (existingIndex === -1) {
            const newIconCoordinates: AnnotationIconProps[] = [
                ...iconsProps,
                {
                    coordinates: {
                        top: element.offsetTop,
                        left: element.offsetLeft,
                    },
                    content: {
                        header: contentHeader,
                        text: contentText,
                    },
                    typeOfAnnotation: hasMultipleAnnotations
                        ? "multiple"
                        : isSystemNotification
                        ? "system"
                        : "single",
                    ids,
                },
            ];
            setIconProps(newIconCoordinates);
        }

export type AnnotationIconProps = {
    coordinates: {
        top: number;
        left: number;
    };
    content: {
        header: string;
        text: string;
    };
    typeOfAnnotation: AnnotationType;
    ids: (string | number)[];
};

I was hoping to have a function in useEffect to check for duplicates, something like

useEffect(() => {
    if (iconsProps.length > visibleAnnotations.length) {
        // function to remove duplicates
    }
}, [iconsProps]);
  • You seem to have some mismatch between `id` and `ids`. What is `ids` in the following? `iconsProps.some((id) => ids.includes(...` also `id` in that `some()` call will be the entire `iconProp` object, perhaps you meant `iconsProps.some(({id}) =>...` (with destructuring?) but that won't work because you set the property as `ids` in your `newIconCoordinates` declaration. – pilchard Oct 27 '22 at 13:03

1 Answers1

0

I'm not sure about the structure of your iconsProps object but maybe this helps:

const idsExistsOnIconProps = iconsProps.some((iconsProb) => ids.includes(iconsProb.id.toString()));
bbasmer
  • 127
  • 2
  • 11