You currently have 3 iterations already in the creation of uniKeys, and would need another iteration to get to your desired output format, resulting in a total of 4 iterations.
Since you need to use some kind of intermediate data structure to eliminate duplicates(1), you can at best bring this down to 2 iterations(2):
- Iteration 1: loop over the input data and build the intermediate data structure (could be a
Set, a Map or
an object) with the intent of eliminating duplicates.
- Iteration 2: extract data from the intermediate data structure to build the output array.
There are many possible variations, but here is one that uses a plain JavaScript object with a reduce() operation for the first iteration, and Object.values() for the second iteration:
const data = [{ id: 1, value: 'a' }, { id: 2, value: 'b' }, { id: 1, value: 'c' }];
const result = Object.values(data.reduce((a, { id }) => {
a[id] ??= { val: `${id}` };
return a;
}, {}));
console.log(result);
(1) There is an approach where you don't build an intermediate data structure and look for potential duplicates in the output array itself (using find() or some()), but this would result in a time complexity of O(n^2) instead of the O(2n) you would get otherwise.
(2) I stand corrected on this. It's trivially doable in one iteration as shown in this answer with a small trade-off in space complexity.
uniKeys....reduce()to build the result, skippingidvalues that have already been seen. Then the array is just the.valuesof the result object.[...set]orArray.from(set)counts as an iteration forset, then you can skip one iteration usingArray.fromwith a map function, see jsFiddle.