Detecting when a value changes when looping an array in Javascript? [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve t开发者_JS百科his questionI have an array where there are repeated values. I need to group like elements, and when the value changes create a new "section".
My array is something like
{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."},
I will need to do something like
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.
Due to the fact that sometimes my array might have fewer or more elements, I need to loop it, and when the value changes create a new heading with the new value and then loop through the elements until the next different item comes up and create the next heading etc.
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."]
}
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);
Assuming they are correctly sorted, and in an array "arr" :
var pre = '';
for (var i = 0; i < arr.length; i++) {
if (arr[i].section != pre) displayHeading(arr[i]);
pre = arr[i];
displayContent(arr[i]);
}
精彩评论