簡體   English   中英

Javascript- 使 JSON 排序功能可擴展到 Date 對象

[英]Javascript- Make JSON sort function extensible for Date object

雖然這個函數對字符串和數字工作正常,因為我對 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;
    }, [])

但不是。

提琴手

替換ret.sort((a, b) => 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];
    }
  });

更新了 jsfiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM