With below code i was able to get duplicate but i am trying to get most recent object from each drug by using transactionDate
property,Below code is only filtering duplicates any idea how to get most recent transaction for each drug.
main.js
var drugsArray = [{
drugName: "ADVIL",
transactionDate: "2018-12-15"
},{
drugName: "ADVIL",
transactionDate: "2018-12-28"
},
{
drugName: "ATRIPLA",
transactionDate: "2018-12-05"
},{
drugName: "ATRIPLA",
transactionDate: "2018-12-21"
}
];
function getDrugs(data) {
let filtered = data.reduce((accumulator, current) => {
if (! accumulator.find(({drugName}) => drugName === current.drugName)) {
var checkRecentDate = getLatestDateSave(current.transactionDate)
if(checkRecentDate) {
accumulator.push(current);
}
}
return accumulator;
}, []);
console.log(filtered);
}
getDrugs(drugsArray);
get the recent date object using this function
function getLatestDateSave(xs) {
if (xs.length) {
return xs.reduce(function(m, i) {
return (i.MeasureDate > m) && i || m;
}, "").MeasureDate;
}
}
Expected output is
result = [{
drugName: "ADVIL",
transactionDate: "2018-12-28"
},
{
drugName: "ATRIPLA",
transactionDate: "2018-12-21"
}
];