簡體   English   中英

JavaScript 按月排序項目列表

[英]JavaScript sort items list by months

我正在玩 js 腳本。 如何按月份對列表項進行排序。 最好的方法是什么?

var dataCollection = [
        { values: { Month: { displayValue: "August" }, Sum: "10" } },
        { values: { Month: { displayValue: "February" }, Sum: "25" } },
        { values: { Month: { displayValue: "July" }, Sum: "35" } }
    ];

我希望得到

dataCollection = [
            { values: { Month: { displayValue: "February" }, Sum: "25" } },
            { values: { Month: { displayValue: "July" }, Sum: "35" } },
            { values: { Month: { displayValue: "August" }, Sum: "10" } }
        ];

您可以通過按正確的順序列出所有月份的列表,並根據它們對數組進行排序來實現:

 var dataCollection = [ { values: { Month: { displayValue: "August" }, Sum: "10" } }, { values: { Month: { displayValue: "February" }, Sum: "25" } }, { values: { Month: { displayValue: "July" }, Sum: "35" } } ]; sortByMonth(dataCollection); console.log(dataCollection); function sortByMonth(arr) { var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; arr.sort(function(a, b){ return months.indexOf(a.values.Month.displayValue) - months.indexOf(b.values.Month.displayValue); }); } 

完全歸功於@ blex上面的答案(已接受的答案),我想擴展一下以確保排序方法......有點增強。

 // 1. Expect an array of Months, long or short format: // ["Jan", "Mar", "Feb"] or ["January", "march", "FEBRUARY"] // 2. Support optional reverse sorting. // 3. Ensure SAFE sorting (does not modify the original array). function sortByMonthName(monthNames, isReverse = false) { const referenceMonthNames = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]; const directionFactor = isReverse ? -1 : 1; const comparator = (a, b) => { if (!a && !b) return 0; if (!a && b) return -1 * directionFactor; if (a && !b) return 1 * directionFactor; const comparableA = a.toLowerCase().substring(0, 3); const comparableB = b.toLowerCase().substring(0, 3); const comparisonResult = referenceMonthNames.indexOf(comparableA) - referenceMonthNames.indexOf(comparableB); return comparisonResult * directionFactor; }; const safeCopyMonthNames = [...monthNames]; safeCopyMonthNames.sort(comparator); return safeCopyMonthNames; } // Examples: const dataset = ["Mar", "January", "DECEMBER", "february"]; const test1 = sortByMonthName(dataset); const test2 = sortByMonthName(dataset, true); 

好吧,有一個非常簡單的解決方案。 上述解決方案也很冗長。

 let dataCollection = [ { values: { Month: { displayValue: "August" }, Sum: "10" } }, { values: { Month: { displayValue: "February" }, Sum: "25" } }, { values: { Month: { displayValue: "July" }, Sum: "35" } }, ]; dataCollection.sort((a, b) => { return ( new Date(`${a.values.Month.displayValue} 2022`) - new Date(`${b.values.Month.displayValue} 2022`) ); }); console.log(dataCollection);

你得到你的排序數據。

暫無
暫無

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

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