Hi am New to Handlebarsjs.
I have a collection of contacts with name, email, phone, etc. as below
[
{
\"name\": \"Bob Wolmer\",
\"email\": \"bo
Lets just say that you have assigned that JSON to a variable named contacts
You can use underscore to group by the first letter of the name property like so:
var groupedContacts = _.groupBy(contacts, function(contact){
return contact.name.substr(0,1);
});
You could then iterate through your groups, maybe sort them and write the content as per your example like this:
_.each(groupedContacts, function (contacts, key) {
console.log(key); // writes the Index letter
// optional sort
var sortedContacts = _.sortBy(contacts, function (contact) {
return contact.name;
});
_.each(sortedContacts, function(contact) {
// Writes the contact name
console.log(contact.name);
});
});
So in a real world application, you would want to replace the console.log
lines with Handlebars templates and/or put it in a helper (however be wary of embedding HTML string in JavaScript as a rule), but thats the easy bit. Also, you may wish sort your groupedContacts
to get the index in order too. You can do this using the same sortBy
method shown in my example above.