【问题标题】:Javascript- Make JSON sort function extensible for Date objectJavascript- 使 JSON 排序函数可扩展为 Date 对象
【发布时间】: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;
    }, [])

但没有。

jsfiddle

【问题讨论】:

  • 你能添加一个你正在使用的函数的例子吗?
  • @pwilcox,我添加了一个小提琴链接

标签: javascript arrays json date


【解决方案1】:

替换ret.sort((a, b) =&gt; a[0] - b[0]);

与:

  ret.sort((a, b) => {
    if (a[0] instanceof Date) {
      return a[0].getTime() - b[0].getTime();
    }
    else {
      return a[0] - b[0];
    }
  });

Updated jsfiddle

【讨论】:

  • 谢谢,但排序不是问题。问题是如何处理累加器中的相等运算符。
  • 那有什么问题呢?你想达到什么目标,为什么?
  • 我正在尝试使该功能可扩展用于保存日期值的键。我正在按键过滤对象数组。键值可以是数字、字符串或日期。
  • 如何将日期转换为 iso 格式 (YYYY-mm-dd) 的字符串,以便使用字典顺序?
猜你喜欢
  • 2015-05-16
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
相关资源
最近更新 更多