let arrayWithDuplicates = []
for(let i = 0; i<1000; i++) {arrayWithDuplicates.push([Math.round(Math.random() * 1000),Math.round(Math.random() * 1000),Math.round(Math.random() * 1000)])}
const lookup = new Map();
for (const record of arrayWithDuplicates) {
const key = record[2];
if (!lookup.has(key)) {
lookup.set(key, record);
continue;
}
const other = lookup.get(key);
if (record[1] > other[1]) {
// Iteration order is based on insertion order. By removing the
// current value first, the new value will be placed at the end.
// If you don't care about the order, deletion can be omitted.
lookup.delete(key);
lookup.set(key, record);
}
}
const result = Array.from(lookup.values());
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])
}
}
let deduped = [...arrayWithDuplicates]; // take a copy
deduped.sort((a, b) => { // sorts in place
if (a[0] < b[0]) return 1; // sort on names
if (a[0] > b[0]) return -1;
return b[1] - a[1]; // sort on second element
})
// reduce into an object keyed on state
deduped = Object.values( // take only the values from the object
deduped.reduce((acc, cur) => {
const state = cur[2];
if (!acc[state]) acc[state] = cur;
return acc;
},{}))