如何处理具有双倍的月份和日以下的数组,否则条件基于月份循环?

inputArray:

var arr = [
            {day: '02',ecount:22,month:"02"},
            {day: '03',ecount:23,month:"02"},
            {day: '01',ecount:21,month:"02"},
            {day: '02',ecount:12,month:"01"},
            {day: '01',ecount:11,month:"01"},
            {day: '03',ecount:13,month:"01"},
        ];


我想获得像
outputArray:

 var newArray = [ [11,12,13],[21,22,23] ]


这是我的代码,但是我失败了!

function stringToNum(str) {
        str = (str.charAt(0) === '0')?parseInt(str.substr(1)):  parseInt(str);

        return str;
    };
    var monthDataArray = [];
    var dateArray = [];
    for(var i=1;i<=12;i++){
        for(var j=0;j<arr.length;j++){
            if(stringToNum(arr[j].month)===i){
                dateArray[stringToNum(arr[j].day)-1]=arr[j].ecount;
                monthDataArray[i-1] = dateArray;
            }
        }
    }

最佳答案

您可以先对数据进行排序,然后通过检查最后一个元素及其月份来进行迭代。然后确定是否需要一个新数组,或者只是将值附加到最后一个数组。



var array = [{ day: '03', ecount:23, month: "02" }, { day: '02', ecount:22, month: "02" }, { day: '01', ecount:21, month: "02"}, { day: '03', ecount:13, month: "01" }, { day: '02', ecount:12, month: "01" }, { day: '01', ecount:11, month: "01" }],
    result;

array.sort(function (a, b) {
    return a.month - b.month || a.day - b.day;
});

result = array.reduce(function (r, a, i, aa) {
    if ((aa[i - 1] || {}).month === a.month) {
        r[r.length - 1].push(a.ecount);
    } else {
        r.push([a.ecount]);
    }
    return r;
}, []);

console.log(result);





for语句。



var array = [{ day: '03', ecount:23, month: "02" }, { day: '02', ecount:22, month: "02" }, { day: '01', ecount:21, month: "02"}, { day: '03', ecount:13, month: "01" }, { day: '02', ecount:12, month: "01" }, { day: '01', ecount:11, month: "01" }],
    result = [],
    i;

array.sort(function (a, b) {
    return a.month - b.month || a.day - b.day;
});

for (i = 0; i < array.length; i++) {
    if ((array[i - 1] || {}).month === array[i].month) {
        result[result.length - 1].push(array[i].ecount);
    } else {
        result.push([array[i].ecount]);
    }
}

console.log(result);





按月和日分组计数,并用零填充缺失值。



var array = [{ day: '03', ecount:23, month: "02" }, { day: '02', ecount:22, month: "02" }, { day: '11', ecount:21, month: "02"}, { day: '03', ecount:13, month: "01" }, { day: '02', ecount:12, month: "01" }, { day: '01', ecount:11, month: "01" }],
    count = Object.create(null),
    result;

array.forEach(function (a) {
    count[a.month] = count[a.month] || Array.apply(null, { length: 32 }).map(function () { return 0; });
    count[a.month][+a.day] += a.ecount;
});

result = Object.keys(count).sort(function (a, b) { return a - b; }).map(function (m) {
    return count[m].slice(1);
});

console.log(result);
console.log(count);

.as-console-wrapper { max-height: 100% !important; top: 0; }

09-25 20:01