基本上每月計算記錄,其中每條記錄都有一個創建日期。
需要一個包含月份名稱 計數作為變數的陣列。
只能用 SQL 做到這一點
這是我的日期時間格式的陣列
[ "2021-10-06", "2021-10-06", "2021-10-06", "2021-10-06", "2021-9-06", "2021-9-06", " 2021-9-06", "2021-9-06", "2021-9-06", ]
uj5u.com熱心網友回復:
使用Array.prototype.reduce()了分組月份和執行計數。
var monthNames = [
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
];
var dates = [ "2021-10-06", "2021-10-06", "2021-10-06", "2021-10-06", "2021-9-06", "2021-9-06", "2021-9-06", "2021-9-06", "2021-9-06"];
var group = dates.reduce(function (r, o){
var date = new Date(o);
var month = date.getMonth();
var monthName = monthNames[month];
(r[monthName]) ? r[monthName].count : r[monthName] = { monthName: monthName, count: 1 };
return r;
}, {});
var result = Object.keys(group).map((key) => group[key]);
console.log(result);
uj5u.com熱心網友回復:
演示頁面
我們通常使用 json 物件來解決此類問題。因為 json 物件可以有字串索引。
杰森:
{
"10":{"cnt" : 4},
"9":{"cnt" : 5},
}
大批:
[["10", 4],["9", 5]]
使用forEach()和entries()來檢索您的陣列
var dates = [ "2021-10-06", "2021-10-06", "2021-10-06", "2021-10-06", "2021-9-06", "2021-9-06", "2021-9-06", "2021-9-06", "2021-9-06"];
let array_month = [];
for (let i = 0; i < dates.length; i ) {
const month = dates[i].split('-')[2];
array_month.push(month);
}
// array_month = ["10", "10", "10", "10", "9", "9", "9", "9", "9"]
let obj = {};
array_month.forEach(function (x) {
// The expression counts[x] || 0 returns the value of counts[x] if it is set, otherwise 0. Then just add one and set it again in the object and the count is done.
obj[x] = (obj[x] || 0) 1;
});
//final = {
// 10: 4,
// 9: 5
//}
//convert object to array
var result = Object.entries(obj);
console.log(result);
//[[MonthName, MonthCount]]
//[["9", 5], ["10", 4]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/342744.html
標籤:javascript 有角的
