var scoringData = [
[22, "Data Structures", 45],
[23, "English", 52],
[22, "English", 51],
[26, "Data Structures", 72],
[23, "Data Structures", 61],
[26, "English", 81]
];
var sorters = [ { key : 1, dir : 1 }, { key : 2, dir : -1 } ];
console.log(retrieveHighest(scoringData, sorters, 1, 0));
function retrieveHighest(data, sorters, categoryIndex, targetIndex) {
var sorter = multiSorter.apply(null, sorters);
return data.sort(sorter).reduce((result, item) => {
if (result[item[categoryIndex]] === undefined) {
result[item[categoryIndex]] = item[targetIndex];
}
return result;
}, {});
}
function multiSorter(sorters) {
var tailArgs = Array.prototype.slice.call(arguments, 1);
return function(a, b) {
var key = typeof sorters === 'object' ? sorters.key : sorters;
var dir = typeof sorters === 'object' ? sorters.dir : 1;
var aV = a[key], bV = b[key];
var equality = (typeof aV === 'string' ? aV.localeCompare(bV) : aV - bV) * dir;
if (equality === 0 && arguments.length > 1) {
return multiSorter.apply(null, tailArgs)(a, b);
}
return equality;
};
}
.as-console-wrapper { top: 0; max-height: 100% !important; }