I have a collection of objects in an array that needs to be sorted and have duplicates removed based on specific values within each object. Currently, I am using two separate loops (not nested) - one for sorting and another for removing duplicates. Is there a more efficient way to accomplish this task? The current code is slow when dealing with thousands of items:
var list = [
{a: "Somename", b: "b", c: 10},
{a: "Anothername", b: "a", c: 12},
// more objects...
];
function sortAndRemoveDuplicates(list) {
// Sort the list based on the specified values
list = list.sort(function(a,b) {
a.a = a.a.toLowerCase();
b.a = b.a.toLowerCase();
if (a.a < b.a) return -1;
if (a.a > b.a) return 1;
a.b = a.b.toLowerCase();
b.b = b.b.toLowerCase();
if (a.b < b.b) return -1;
if (a.b > b.b) return 1;
if (a.c < b.c) return -1;
if (a.c > b.c) return 1;
return 0;
});
// Loop through the list to remove duplicates
for (var a,b,i=list.length-1; i > 0; i--) {
a = list[i];
a.a = a.a.toLowerCase();
a.b = a.b.toLowerCase();
b = list[i-1];
b.a = b.a.toLowerCase();
b.b = b.b.toLowerCase();
if (a.a === b.a && a.b === b.b && a.c === b.c) list.splice(i-1,1);
}
return list;
}
list = sortAndRemoveDuplicates(list);
Please refrain from suggesting jQuery solutions or the use of additional libraries. It seems unnecessary to import a library for such a simple task.