I have a solution that will filter my array of objects for unique values, however it is tightly coupled to the actual elements of those objects…
For example:
const makeObj = (val, type) => ({ val, type });
const arr = [
makeObj('123', 'val1'),
makeObj('123', 'val1'),
makeObj('321','val2'),
makeObj('321','val2'),
makeObj('321','val1'),
]
const res = arr.filter((value, index, self) =>
self.findIndex(v => (v.val === value.val) && (v.type === value.type)) === index);
The issue I’m looking at is of course, what happens if we want to add more and more properties to the object? NOTE: All objects will have the same properties.
I know it would be possible to replace the comparator (v.val === value.val) && (v.type === value.type)
with JSON.stringify(v) === JSON.stringify(val)
and all should be good… However, I’m aware that this wouldn’t work for functions as values etc..
My initial thought was, could we extract the list of properties from one the objects, then iterate over them to perform the checks? This would assume that there are there are the same keys available in each of the objects.