【发布时间】:2020-09-02 15:19:41
【问题描述】:
虽然此函数适用于字符串和数字,但因为我将 === 比较运算符用于 Date 对象,但它不会扩展。
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;
}
我试过了:
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;
}, [])
但没有。
【问题讨论】:
-
你能添加一个你正在使用的函数的例子吗?
-
@pwilcox,我添加了一个小提琴链接
标签: javascript arrays json date