var events = [/* as in the question */];
var groupedEvents = {};
for (var i = 0; i < events.length; ++i) {
var time = events[i].section;
var action = events[i].title;
if (!groupedEvents.hasOwnProperty(time)) {
groupedEvents[time] = [];
}
groupedEvents[time].push(action);
}
现在groupedEvents包含:
{
"An Hour before Dinner": ["Cook peas", "Take pie out"],
"As guests arrive": ["Mix Drinks"],
"Just before dessert": ["Reheat at 325 about 20 minutes.", "Cut and serve."]
}
var events = [/* as in the question */];
var groupedEvents = {};
for (var i = 0; i < events.length; ++i) {
var time = events[i].section;
var action = events[i].title;
if (!groupedEvents.hasOwnProperty(time)) {
groupedEvents[time] = [];
}
groupedEvents[time].push(action);
}
Now groupedEvents contains:
{
"An Hour before Dinner": ["Cook peas", "Take pie out"],
"As guests arrive": ["Mix Drinks"],
"Just before dessert": ["Reheat at 325 about 20 minutes.", "Cut and serve."]
}
var arr = [
{section:"An Hour before Dinner", title:"Cook peas"},
{section:"An Hour before Dinner", title:"Take pie out"},
{section:"As guests arrive", title:"Mix drinks"},
{section:"Just Before Dessert", title:"Reheat at 325 about 20 minutes."},
{section:"Just Before Dessert", title:"Cut and serve."}
];
var s = null;
var html = "";
for (var i = 0, l = arr.length; i<l; i++) {
var r = arr[i];
if (r.section != s) {
// New section
s = r.section;
html += "<h1>"+s+"</h1>"
} else {
// Continue old section
}
html += "<p>"+r.title+"</p>";
}
var div = document.createElement('div');
div.innerHTML = html;
document.body.appendChild(div);
This should do the trick:
var arr = [
{section:"An Hour before Dinner", title:"Cook peas"},
{section:"An Hour before Dinner", title:"Take pie out"},
{section:"As guests arrive", title:"Mix drinks"},
{section:"Just Before Dessert", title:"Reheat at 325 about 20 minutes."},
{section:"Just Before Dessert", title:"Cut and serve."}
];
var s = null;
var html = "";
for (var i = 0, l = arr.length; i<l; i++) {
var r = arr[i];
if (r.section != s) {
// New section
s = r.section;
html += "<h1>"+s+"</h1>"
} else {
// Continue old section
}
html += "<p>"+r.title+"</p>";
}
var div = document.createElement('div');
div.innerHTML = html;
document.body.appendChild(div);
发布评论
评论(3)
现在
groupedEvents
包含:Now
groupedEvents
contains:这应该可以解决问题:
This should do the trick:
假设它们已正确排序,并且位于数组“arr”中:
Assuming they are correctly sorted, and in an array "arr" :