I wrote code to remove the duplicates from an array, but I feel it could be made more elegant. Suggestions Please.
Interface Definition
export interface SomeClass {
version: number,
typeDescription: string
}
Test Data
sthClass: SomeClass[] = [
{ typeDescription: "typeA", version: 10 },
{ typeDescription: "typeA", version: 21 },
{ typeDescription: "typeB", version: 101 },
{ typeDescription: "typeC", version: 199 },
{ typeDescription: "typeA", version: 220 },
{ typeDescription: "typeB", version: 33 },
{ typeDescription: "typeA", version: 15},
];
Business Logic to Remove duplicates and keep the one that has largest version number
for (let index = this.sthClass.length - 1; index >= 0; index--) {
filterArr = this.sthClass.filter(item => item.typeDescription == this.sthClass[index].typeDescription);
if (filterArr.length > 1) {
//sort in Desc Order
filterArr.sort((a: SomeClass, b: SomeClass) => b.version - a.version);
let idx = this.sthClass.findIndex(k => filterArr[1] === k)
this.sthClass.splice(idx, 1);
}
}
2
Answers
One way to do it in linear time is using
reduce()
and a JS obejct (alternatively aMap
) to efficiently lookup whether atypeDescription
with that value has already been encountered and if it was whether the version of the current item is higher. Finally you can then obtain the values usingObject.values()
.Alternatively:
A working, yet slower (
O(n log n)
compared toO(n)
above) and to my mind also less elegant solution using sorting can also be created.typeDescription
and then version in descending ordertypeDescription
Here is my Solution:-
The output of the code will be an object that contains unique typeDescription as keys and the largest version number for each typeDescription as values.