Javascript字母分组 [英] Javascript alphabetical grouping
本文介绍了Javascript字母分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象的json数组,如下所示:{id:'the id', name:'the name'};
,我需要遍历该数组,并按其name属性按字母顺序对每个对象进行分组.有没有一种方法,而无需使用带有每个字母的switch/if语句?
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') {
...
}
这是一个大型数组,其中包含近1,000个对象.我的目标是最终将他们添加到潜水中,这样看起来像这样:
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个饼干
- 苹果
- 亚历克斯
- 亚当
- 鲍勃
- 比利
推荐答案
您可以像这样循环遍历您的收藏集:
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...}
这篇关于Javascript字母分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文