Search code examples
javascriptyuiyui3

Javascript alphabetical grouping


I have a json array of objects that look like this: {id:'the id', name:'the name'}; and I need to loop over the array and group each object alphabetically by it's name attribute. Is there a way to do this without using a switch / if statement with every letter in it?

What I don't want to do is something like this:

if(data[i].name..slice(0, 1) == 'a') {
   ...
}

It's a large array, with almost a 1,000 objects in it. My goal is eventually append them to a dive so it looks something like this:

4

  • 4 pints
  • 4 biscuits

A

  • Apple
  • Alex
  • Adam

B

  • Bob
  • Billy

Solution

  • you can loop throught your collections like this:

    var groupedCollection = {};   
    for(...){//loop throug collection         
        var firstLetter = data[i].charAt(0);
        if(groupedCollection[firstLetter] == undefined){             
            groupedCollection[firstLetter] = [];         
        }         
        groupedCollection[firstLetter].push(data[i]);     
    }
    //groupedCollection now contait data in the form of {a: [], b:[], etc...}