Parse Data And Order Alphabetically Under Letter
This is what I would like to become: This is my javascript: var retrievedObject = localStorage.getItem('exhibitor'); // CALL FUNCTION parsePerObject(JSON.parse(retrieved
Solution 1:
Say you have an Array
of objects, not an Object
of objects, to enable indexing and sorting. Objects don't have order.
You retrieve it from localStorage
. You parse it.
var people = JSON.parse(localStoarge.getItem("exhibitor");
// now you have an array of objects, each object representing a person.// regardless of what structure you have now, change it to achieve this.var comparePersons = function(a, b) {
// this function will compare two people objects.return a.name.localeCompare(b.name);
// it's using String.prototype.localeCompare which returns 1 if a.name > b.name,// 0 for equal and -1 for smaller. localeCompare is lexicographic comparison.
};
people.sort(comparePersons);
// now you have the people sorted alphabetically.
You can run through the people array, get the unique start letters, make an array of out them, and then display data as you want. It should be fairly simple.
var letters = '', groups = {};
for (var i = 0, len = people.length; i < len; i++) {
var letterKey = people[i].name.charAt(0).toLowerCase();// get the first letterif (letters.indexOf(letterKey)) == -1) {
letters += letterKey;
groups[letterKey] = [people[i]];// index the people by unique letters.
} else {
groups[letterKey].push([people[i]]);// add to the existing list. Another Syntax fix
};
};
At this point you have an object like this:
a: [person1, person2, person5, etc..]//the people at A.
b: [person 3, person 4, etc..]// the people at B.
Just use the above data to create the display. Anything more and I would have to invoice you:).
The tricks here are Array.prototype.sort
(here is more on it) and String.prototype.localeCompare
(read more here).
Post a Comment for "Parse Data And Order Alphabetically Under Letter"