How to filter this array
var arr = [[1, "3/20/2018", "A"], [1, "3/20/2018", "B"],
[1, "4/20/2018", "A"], [1, "4/20/2018", "B"],
[2, "1/30/2018", "A"], [2, "1/30/2018", "B"],
[2, "3/30/2018", "A"], [2, "3/30/2018", "B"]
];
I want to filter only the elements with the latest dates per other sub-elements (ID) . To have this output:
var result = [[1, "4/20/2018", "A"], [1, "4/20/2018", "B"],
[2, "3/30/2018", "A"], [2, "3/30/2018", "B"]
];
Some observations/assumptions
3/20/2018
. Without quotes this will only be a floating numberBased on the above, you can try following
var arr = [[1, "3/20/2018", "A"], [1, "3/20/2018", "B"], [1, "4/20/2018", "A"], [1, "4/20/2018", "B"], [2, "1/30/2018", "A"], [2, "1/30/2018", "B"], [2, "3/30/2018", "A"], [2, "3/30/2018", "B"]];
var obj = {};
arr.forEach(function(item){
var id = item[0] + "_" + item[2];
if(obj[id]) {
if(new Date(item[1]) > new Date(obj[id][1])) {
obj[id] = item;
}
} else {
obj[id] = item;
}
});
console.log(Object.values(obj));