gpt4 book ai didi

javascript - 使用下划线填充数组中缺失的对象

转载 作者:行者123 更新时间:2023-11-29 19:10:23 25 4
gpt4 key购买 nike

我正在玩一个数据集,该数据集计算一个人在特定时间做出的提交次数。我可以为一个人提交的时间和他们提交的次数创建一个数组对象:

[ { hour: '6', commits: 2 },
{ hour: '7', commits: 6 },
{ hour: '8', commits: 6 },
{ hour: '9', commits: 4 },
{ hour: '10', commits: 4 },
{ hour: '11', commits: 6 },
{ hour: '12', commits: 18 },
{ hour: '13', commits: 18 },
{ hour: '14', commits: 14 },
{ hour: '15', commits: 30 },
{ hour: '16', commits: 24 },
{ hour: '17', commits: 18 },
{ hour: '18', commits: 24 },
{ hour: '19', commits: 22 },
{ hour: '20', commits: 6 },
{ hour: '21', commits: 16 },
{ hour: '22', commits: 8 } ]

我被困的地方是试图填补缺失的时间。所以在上面的例子中,我需要包括没有提交的时间。我一整天都在使用 0-24 范围。这是我希望得到的结果:

[
{ hour: '0', commits: 0 },
{ hour: '1', commits: 0 },
{ hour: '2', commits: 0 },
{ hour: '3', commits: 0 },
{ hour: '4', commits: 0 },
{ hour: '5', commits: 0 },
{ hour: '6', commits: 2 },
{ hour: '7', commits: 6 },
{ hour: '8', commits: 6 },
{ hour: '9', commits: 4 },
{ hour: '10', commits: 4 },
{ hour: '11', commits: 6 },
{ hour: '12', commits: 18 },
{ hour: '13', commits: 18 },
{ hour: '14', commits: 14 },
{ hour: '15', commits: 30 },
{ hour: '16', commits: 24 },
{ hour: '17', commits: 18 },
{ hour: '18', commits: 24 },
{ hour: '19', commits: 22 },
{ hour: '20', commits: 6 },
{ hour: '21', commits: 16 },
{ hour: '22', commits: 8 },
{ hour: '23', commits: 0 },
{ hour: '24', commits: 0 }
]

这是我用来创建这些对象的函数:

var getAuthorAndHourCounts = (groupedByAuthor) => {

var result = _.map(groupByAuthor, (value, key, list) => {

var author = key;
var hours = _.countBy(value, 'hour');

var commitHourList = [];

_.each(hours, (v,k) => {
var obj = {};
obj.hour = k;
obj.commits = v;
commitHourList.push(obj);
});

return {
person: author,
times: commitHourList
};

});
return result;
};

如何添加缺失的时间?我正在考虑创建一个列表 (0-24),然后查看列表中是否有一个小时以将其添加为零值到对象。不确定如何实现。

最佳答案

如何初始化 commitHourList,使其包含所有提交了 0 的时间,然后用实际数据填充它:

// initialize commitHourList with 24 objects 
// one for each hour and each with 0 commits
var commitHourList = _.range(24).map((hour) => ({ hour, commits: 0 }));

// for every received hour, add proper commits
_.each(hours, (commits, hour) => {
commitHourList[hour].commits = commits;
});

这样,无论您不添加什么时间,都会自动进行 0 次提交。

注意:使用range 然后使用map 来初始化数组的代码较少,但每次都会迭代数组两次。一种更高效的方法是在某个实用程序中创建此数组一次,然后在每次需要新数组时复制它。

例如:

// utility that creates the hours array when initialized
// and returns a function that will return a copy of the hours array on each call
var getHoursArray = (function() {
var arr = _.range(24).map((hour) => ({ hour, commits: 0 }));
return function() {
return arr.slice();
}
})();

然后像这样使用它:

var commitHourList = getHoursArray();

使用 slice 通常是复制数组的最有效方法,但 here are other possibilities

关于javascript - 使用下划线填充数组中缺失的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39302502/

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