好的,我得到了一个数组中的对象数组。它们实际上是关联数组。所以它实际上是一个关联数组的数组。
控制台日志输出如下所示:
[array object] [object{...},object{...},object{...}, etc...]
每个对象都有名称、价格和颜色。我想要的是将它们按字母顺序和价格升序或降序排序。
我有一个将它们放到页面上的jQuery代码,但我需要插入一些代码,以便按我选择的顺序放置它们。有什么想法吗?
发布于 2014-09-20 17:07:48
您可以使用接受比较函数作为参数的javascript数组排序方法。
var a = [{name: 'a', price: 1, color: 'red'},
{name: 'b', price: 2, color: 'red'},
{name: 'c', price: 3, color: 'blue'}];
// Ascending order
a.sort(function (a, b) {
return a.price - b.price;
});
// Descending order
a.sort(function (a, b) {
return b.price - a.price;
});
编辑:如果您需要先按名称升序排序,然后按价格升序或降序排序,则:
// Sort by name in ascending order first and then by price in ascending order
a.sort(function (a, b) {
return a.name.localeCompare(b.name) || a.price - b.price;
});
// Sort by name in ascending order first and then by price in descending order
a.sort(function (a, b) {
return a.name.localeCompare(b.name) || b.price - a.price;
});
发布于 2014-09-20 17:02:11
您可以使用Array#sort
对数组进行排序。它接受一个比较器回调函数( sort
算法可以用来比较两个条目,看看哪一个应该先出现),并对数组进行就地排序(例如,它不会复制数组)。契约是:使用两个条目调用比较器,如果第一个条目应该在第二个条目之前,则返回<0
;如果它们相等,则返回0
;如果第一个条目应该在第二个条目之后,则返回>0
:
yourArray.sort(function(a, b) {
// return <0 if a is less than b
// 0 if a is equal to b
// >0 if a is greater than b
});
可以使用String#localeCompare
按字母顺序比较名称;它可以方便地返回<0
、0
或>0
。如果名称比较没有返回0
,则返回它返回的内容;如果名称比较返回0
,则返回a.price - b.price
。
https://stackoverflow.com/questions/25951114
复制相似问题