gpt4 book ai didi

javascript - 如何使用double for 语句创建一个循环来排序Array 来处理有月和日的Array?

转载 作者:行者123 更新时间:2023-11-30 15:21:34 25 4
gpt4 key购买 nike

如何处理下面的数组,其中有月份和日期使用 double if else 条件基于月份循环?

输入数组:

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"},
];

我想获取像这样的数据输出数组:

 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; }

关于javascript - 如何使用double for 语句创建一个循环来排序Array 来处理有月和日的Array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43652154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com