按属性对对象数组进行排序
我有来自数据库的这个集合:
I have this collection from DataBase:
var items = [{ 'Name':'Michael', 'TypeId':1 }
{ 'Name':'Max', 'TypeId':1 }
{ 'Name':'Andre', 'TypeId':1 }
{ 'Name':'Georg', 'TypeId':2 }
{ 'Name':'Greg', 'TypeId':3 }
{ 'Name':'Mitchell', 'TypeId':2 }
{ 'Name':'Ptro', 'TypeId':1 }
{ 'Name':'Helga', 'TypeId':1 }
{ 'Name':'Seruin', 'TypeId':2 }
{ 'Name':'Ann', 'TypeId':3 }
{ 'Name':'Marta', 'TypeId':2 }]
我需要按 TypeId 递增对这些项目进行排序.
I need to sort this items by TypeId increasing.
像这样:
var itemsSorted = [{ 'Name':'Michael', 'TypeId':1 }
{ 'Name':'Max', 'TypeId':1 }
{ 'Name':'Andre', 'TypeId':1 }
{ 'Name':'Ptro', 'TypeId':1 }
{ 'Name':'Helga', 'TypeId':1 }
{ 'Name':'Georg', 'TypeId':2 }
{ 'Name':'Mitchell', 'TypeId':2 }
{ 'Name':'Marta', 'TypeId':2 }]
{ 'Name':'Seruin', 'TypeId':2 }
{ 'Name':'Greg', 'TypeId':3 }
{ 'Name':'Ann', 'TypeId':3 }
JavaScript 中是否有任何内置函数可以按属性对对象数组进行排序?
Is there any built in function in JavaScript that can sort array of objects by property?
您可以使用 orderBy
过滤器.
You could use orderBy
filter.
var itemsSorted = $filter('orderBy')(items, 'TypeId')
正在查看
ng-repeat="item in items | orderBy: 'TypeId'"
默认过滤器是升序的(显式是 +TypeId
),你可以使用 -TypeId
使其降序.
By default filters are ascending(explicit would be +TypeId
), you could use -TypeId
to make it descending.
其他内容
如果你想按多个属性排序,那么请使用数组而不是 string
像 ['TypeId', 'Name']
If you wanted to sort by multiple properties then do use array instead of string
like ['TypeId', 'Name']
ng-repeat="item in items | orderBy: ['TypeId', 'Name']"
当您在控制器内部进行手动过滤时,您将获得巨大的性能优势.其中视图过滤较慢,因为它每次在摘要循环触发时评估 ng-repeat
表达和绑定.通常,您不会在小集合中看到任何性能下降,但在较大的集合中,您会发现视图过滤工作缓慢.
There is big performance benefit you get when you do manual filtering inside controller. where as filtering on view is slower as it evaluates ng-repeat
express and bindings each time when digest cycle fire. Generally you won't see any performance hit in small collection, but in bigger collection you will see filtering on view will work slow.