Sets don't remove objects that have different references. Even if the object has the same values these objects aren't considered the same:
const arr = [
// These objects look the same but are both unique objects in memory, so they have different references
{foo: 1},
{foo: 1}
];
const res = [...new Set(arr)];
console.log(res); // [{foo: 1}, {foo: 1}]
Your case is similar to the above example, as the JSX <option ...></option>
are creating objects behind the scenes.
Instead, I suggest that you use a different method to deduplicate your devices
array from the duplicate objects. You can perform this deduplication only when your devices
array changes with the help of useMemo()
(assuming devices
is state), for example:
const uniqueDevices = useMemo(() => {
const uniqueMap = new Map(devices.map(device => [
device.device_id, // deduplicate by the `device_id` property
device
]);
return [...uniqueMap.values()];
}, [devices]);
// please post your code as text so we don't have to retype this :)
return <div>
<h1>Devices</h1>
<select>
{ devices ?
? uniqueDevices.map(device => <option key={device.device_id}>{device.device_id}</option>)
: null
}
</select>
</div>
If you only need to refer to the device_id
property in your JSX from each device
object, then you can continue to use a Set()
to remove your duplicates as @andrew suggests, eg:
const uniqueDeviceIds = useMemo(() =>
Array.from(new Set(devices.map(device => device.device_id)))
, [devices]);
return <div>
<h1>Devices</h1>
<select>
{ devices ?
? uniqueDeviceIds.map(deviceId => <option key={deviceId}>{device_id}</option>)
: null
}
</select>
</div>
Devices