Although this function functions properly with strings and numbers, it encounters problems when Date objects are involved due to the use of the ===
comparison operator.
function getDataCounted(objects, key) {
let ret = [];
let groups = objects
.reduce((accumulator, element, index, array) => {
if (accumulator.indexOf(element[key]) < 0 &&
array.findIndex(elm => elm[key].getTime() === array[key].getTime()) < index)
accumulator.push(element[key]);
return accumulator;
}, [])
.forEach(group => {
let count = 0;
objects.forEach(object => {
if (object[key] === group) {
count++;
}
});
ret.push([
group,
count
])
});
ret.sort((a, b) => a[0] - b[0]);
return ret;
}
I attempted to address this by:
let groups = objects
.reduce((accumulator, element, index, array) => {
if (element instanceof Date) {
if (accumulator.indexOf(element[key]) < 0 //
&&
array.findIndex(elm => elm[key].getTime() === array[key].getTime()) < index)
accumulator.push(element[key]);
return accumulator;
}
if (accumulator.indexOf(element[key]) < 0 &&
array.findIndex(elm => elm[key] === array[key]) < index)
accumulator.push(element[key]);
return accumulator;
}, [])
However, it did not resolve the issue.