当前位置: 代码迷 >> JavaScript >> 使用JavaScript按月和年创建内部数组组
  详细解决方案

使用JavaScript按月和年创建内部数组组

热度:18   发布时间:2023-06-05 10:16:20.0

我有一个数组看起来像:

var v = ["07/27/2015", "07/28/2015", "08/29/2015", "08/29/2015", "07/27/2016"]

我想要做的是将其动态地排序为一个新的空数组nv 排序完成后, nv应该看起来像。

var nv = [["07/27/2015", "07/28/2015"], ["08/29/2015", "08/29/2015"], ["07/27/2016"]]

这样可以排序吗?

var dates = ["07/27/2015", "07/28/2015", "08/29/2015", "08/29/2015", "07/27/2016"];

var groupedDates = dates.reduce(function(l, r) {
    var keyParts = r.split("/"),
        key = keyParts[2] + keyParts[0];

    if (typeof l[key] === "undefined") {
        l[key] = [];
    }

    l[key].push(r);

    return l;
}, {});

var result = Object.keys(groupedDates)
                    .sort(function(a, b) { return Number(a) - Number(b); })
                    .map(function(key) {
                        return groupedDates[key];
                    });

console.log(result);    // [["07/27/2015","07/28/2015"],["08/29/2015","08/29/2015"],["07/27/2016"]]

因此,我做了一个函数,将日期放入属性为月和年的对象中。 日期被放入其月份和年份的属性中。 然后,该函数创建一个数组,并为该函数的每个属性创建一个内部数组。 在每个内部数组中,它放置该属性的所有日期。 我认为这种方法比嵌套循环更有效。

// function takes an array of dates in the following format MM/DD/YYYY
// outputs an array with inner arrays of dates. Each inner array contains dates of the same month and year
var groupDates = function(dateArray) {
    // create object to organize dates by month and year
    var dateHash = {};
    // the array that is outputted
    var groupedDates = [];

    //for every date in dateArray
    dateArray.forEach(function(currentDate) {
        // check if any other dates with the same month and year exist in the dateHash object
        if (dateHash[currentDate.substr(0, 2) + currentDate.substr(6)]) {
            // if other dates exist, push the date to the array in the dateHash property for the dates current month and year
            dateHash[currentDate.substr(0, 2) + currentDate.substr(6)].push(currentDate);
        } else {
            // otherwise create a property for the dates month and year and store the current date in an array in the propery
            dateHash[currentDate.substr(0, 2) + currentDate.substr(6)] = [currentDate];
        }
    });

    // for every propery in the datehash, push the array of dates into the grouped dates array
    for (var dateGroup in dateHash) {
        groupedDates.push(dateHash[dateGroup]);
    }
    return groupedDates;
};

var dateArray = ["07/27/2015", "07/28/2015", "08/29/2015", "08/29/2015", "07/27/2016"];
console.log(groupDates(dateArray));

您可以遍历该数组并检查每个值是否具有新的月份和年份,或者已包含在排序数组中。 我认为像这样未经测试的代码:

new_arr = new Array();
for(var i=0; i < v.length; i++){
    var this_date = new Date(v[i]);
    var month_and_year = this_date.getMonth() + this_date.getFullYear();
    if(typeof(new_arr[month_and_year]) == 'undefined'){
         new_arr[month_and_year] = new Array();
    }
    new_arr[month_and_year].push(v[i])
} 
  相关解决方案