I have an array of objects with a name property...
var myList = [{
name: 'Apple'
}, {
name: 'Nervousness',
}, {
name: 'Dry'
}, {
name: 'Assign'
}, {
name: 'Date'
}]
Essentially, I am trying to create an array set up like this:
[{
name: 'A',
items: [{
name: 'Apple'
}, {
name: 'Assign'
}]
}, {
name: 'D',
items: [{
name: 'Date',
}, {
name: 'Dry',
}]
}, {
name: 'N',
items: [{
name: 'Nervousness',
}]
}];
Basically, my array of objects needs to be alphabetized, placed into a new object with a parent key/value of 'name' with the corresponding letter.
I can alphabetize them as follows...
myList.sort(function (a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
Then I can create an array of the first letters...
var headerLetters = [];
angular.forEach(myList, function (item) {
var firstLetter = item.name.charAt(0);
if (headerLetters.indexOf(firstLetter) === -1) {
headerLetters.push(firstLetter);
}
});
But then this is where I am stuck... I can check for duplicate first letters, but then how would I iterate through my list of objects and push them into a new object array in alphabetical order?