user2332277 - 7 months ago 30
Javascript Question

2D Array or Map to store values against weekdays and slots within days

I want to increment values for days of week and slots within each day, i.e. Morning, Afternoon, Evening and Night, as I iterate over a collection where I get the time and then evaluate which timeslot the time is in.
I need to be able to iterate over the end result in the front end but want a nicer solution that the one i currently have represented but the totals array. It has been suggested I use a map but unsure of how to implement this with a map.

``````   var totals = [
//  Tot M  T  W  T  F  S  S
[0, 0, 0, 0, 0, 0, 0, 0],    // Totals
[0, 0, 0, 0, 0, 0, 0, 0],    // Morning
[0, 0, 0, 0, 0, 0, 0, 0],    // Afternoon
[0, 0, 0, 0, 0, 0, 0, 0],    // Evening
[0, 0, 0, 0, 0, 0, 0, 0]     // Night
];

var collectionOfData = entiredataset;

collectionOfData.forEach(function (item) {
var localDate = getLocalDate(item);//gets users local date and determines timeslot id - ie Morning,afternoon, evening, or night
var dayOfWeek = localDate.day();
var timeslotId = item.timeslotId;

totals[timeslotId][dayOfWeek]++;  // Increase sessions per slot and day
totals[0][dayOfWeek]++;           // Increase total sessions per day
totals[timeslotId][0]++;    // Increase total sessions per slot
totals[0][0]++;             // Increase total sessions

}
``````

Any suggestions would be much appreciated.

One of the ways I would design the data structure is as follows - see demo with input, output and total calculation methods:

``````var slots={'Monday':{'Morning':0,'Afernoon':0,'Evening':0,'Night':0},'Tuesday':{'Morning':0,'Afernoon':0,'Evening':0,'Night':0},'Wednessday':{'Morning':0,'Afernoon':0,'Evening':0,'Night':0},'Thursday':{'Morning':0,'Afernoon':0,'Evening':0,'Night':0},'Friday':{'Morning':0,'Afernoon':0,'Evening':0,'Night':0},'Saturday':{'Morning':0,'Afernoon':0,'Evening':0,'Night':0},'Sunday':{'Morning':0,'Afernoon':0,'Evening':0,'Night':0},}

// input data
function insertSlotFor(day, slot) {
slots[day][slot]++;
}

// output data
function getSlotFor(day, slot) {
return slots[day][slot];
}

// get total for a day
function totalForDay(day) {
return Object.keys(slots[day]).reduce(function(prev,curr){
return prev + slots[day][curr];
},0);
}

// get total for a slot
function totalForSlot(slot) {
return Object.keys(slots).reduce(function(prev,curr){
return prev + slots[curr][slot];
},0);
}

insertSlotFor('Monday', 'Morning');
insertSlotFor('Monday', 'Night');
insertSlotFor('Tuesday', 'Morning');

console.log(slots);

console.log(totalForDay('Monday'));
console.log(totalForSlot('Morning'));``````
``.as-console-wrapper{top:0;max-height:100%!important;}``