Javascript按字母顺序分组

imn*_*mns 1 javascript yui yui3

我有一个json数组的对象看起来像这样:{id:'the id', name:'the name'};我需要循环遍历数组并按名称属性按字母顺序对每个对象进行分组.有没有办法在不使用带有每个字母的switch/if语句的情况下执行此操作?

我不想做的是这样的事情:

if(data[i].name..slice(0, 1) == 'a') {
   ...
}
Run Code Online (Sandbox Code Playgroud)

它是一个大型数组,其中包含近1,000个对象.我的目标是最终将他们添加到潜水中,所以它看起来像这样:

4

  • 4品脱
  • 4块饼干

一个

  • 苹果
  • 亚历克斯
  • 亚当

  • 短发
  • 比利

isr*_*a17 8

你可以像这样循环你的集合:

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...}
Run Code Online (Sandbox Code Playgroud)