I have a code that removes duplicates from an array, but I believe it could be improved for better elegance. Any suggestions?
Interface Definition
export interface SomeClass {
version: number,
typeDescription: string
}
Test Data
someClasses: 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 with the highest version number
for (let index = this.someClasses.length - 1; index >= 0; index--) {
filterArr = this.someClasses.filter(item => item.typeDescription == this.someClasses[index].typeDescription);
if (filterArr.length > 1) {
//sort in Desc Order
filterArr.sort((a: SomeClass, b: SomeClass) => b.version - a.version);
let idx = this.someClasses.findIndex(k => filterArr[1] === k)
this.someClasses.splice(idx, 1);
}
}