我有一个名为open的数组,其中我每天都有从0到6开始索引的数组。在每天的数组中,我有时间和一天设置。在某些日子里,时间会相同,因此想要对相同的值进行分组。例如
open[] -> [0] -> {open: 12:00, close: 16:00, Monday}
[1] -> {open: 12:00, close: 16:00, tuesday}
我如何对这些值进行分组,以便我可以拥有一个具有时间和与之相关的所有日期的数组。或者这些日子最好的展示方式就是这个时候。
这个开放数组也可以包含不同的时间,例如:
open[] -> [0] -> {open: 12:00, close: 16:00, monday}
[1] -> {open: 12:00, close: 16:00, tuesday}
[1] -> {open: 14:00, close: 16:00, sunday}
感谢任何帮助!
答案 0 :(得分:0)
我不确定我是否100%理解您的要求,但根据您所说的内容,我认为您希望根据具有相同的开放性和时间性来对一周中的几天进行分组。关闭时间。要做到这一点,你可以通过连接open和amp;来创建一个“密钥”。关闭时间,然后使用此键在对象中查找组数组。这是一个例子:
//Set up an array of randomized test data
var initTestData = function(){
var testReferenceData = {
openTimes: ["08:00","08:30","09:00"],
closeTimes: ["05:00","05:30"],
daysOfWeek: ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
}
var data = [];
for(var d=0; d<testReferenceData.daysOfWeek.length; ++d){
var randOpen = Math.floor(Math.random() * testReferenceData.openTimes.length),
randClose = Math.floor(Math.random() * testReferenceData.closeTimes.length);
var day = {
day: testReferenceData.daysOfWeek[d],
open: testReferenceData.openTimes[randOpen],
close: testReferenceData.closeTimes[randClose]
};
data.push(day);
}
return data;
}
//Group days by times
var groupByTime = function(days){
var groups = {};
for(var d=0; d<days.length; ++d){
//Create a key by concatenating the start & end times of a day
var key = days[d].open+"_"+days[d].close;
//If this is the first one, initialize an array
if(!groups[key]){
groups[key] = [];
}
//Add the day to the group by its key
groups[key].push(days[d]);
}
//Return an array of our groups
return Object.values(groups);
}
var open = initTestData();
console.log("Initial array", open);
var grouped = groupByTime(open);
console.log("Grouped array", grouped);