What is the most efficient method to dedupe a complex array based on the value of another property? I have found many examples that will dedupe an array or complex array but not this specific use case.
I am trying to find records with unique values in column 3 (state) with the highest number in column 2 (license)
var arrayWithDuplicates = [
["Boat", 1, "NV"],
["Car", 7, "CA"],
["Boat", 3, "NV"],
["Boat", 4, "CA"],
["Car", 5, "OR"],
["Boat", 6, "CA"],
];
Desired outcome
var outputArray = [
["Car", 7, "CA"],
["Boat", 3, "NV"],
["Car", 5, "OR"]
];
This works but not sure if with large datasets
var arrayWithDuplicates = [
["Boat", 1, "NV"],
["Car", 7, "CA"],
["Boat", 3, "NV"],
["Boat", 4, "CA"],
["Car", 5, "OR"],
["Boat", 6, "CA"],
];
let arr= arrayWithDuplicates;
let unique = []
for (let i = 0; i < arr.length; i++) {
let found = false;
for (let j = 0; j < unique.length; j++) {
if (arr[i][2] === unique[j][2]) {
found = true;
if (arr[i][1] > unique[j][1]) {
unique[j] = arr[i];
}
break;
}
}
if (!found) {
unique.push(arr[i])
}
}
console.log(unique);
[["Boat", 3, "NV"], ["Boat", 7, "CA"], ["Car", 5, "OR"]]
You can see the performance of the proposed solutions: https://jsbench.me/eskxxcwnhn/1