2012-03-08 58 views
0

我已经看到了问题和答案如何按一个值(文本或数字)和两个数字(年和数的东西)排列数组。如何在JavaScript中通过两个名称对数组进行排序?

如何按升序排序一个字符串,以特殊顺序排列另一个字符串?

这里是阵列

var stop = { 
    type: "S", // values can be S, C or H. Should ordered S, C and then H. 
    street: "SW Dummy St." // Should be sorted in ascending order 
} 

一个对象,并预计最终的结果应该是这样的

var data = [ 
    { type: 'S', year: 'SW Karp' }, 
    { type: 'S', year: 'SW Walker' }, 
    { type: 'C', year: 'SW Greth' }, 
    { type: 'C', year: 'SW Main' } 
    { type: 'H', year: 'SW Dummy' } 
]; 
+1

可能重复(http://stackoverflow.com/问题/ 6913512/how-to-sort-an-array-of-objects-by-multiple-fields) – 2012-03-08 13:28:01

+0

只需确保:您可以在我的答案中使用该函数,并为'type'使用特殊引物,返回,例如每个字母都有一个数字,例如'S'为'0','C'为'1','H'为'2':'data.sort(sort_by({name:'type',primer:function x){return({'S':0,'C':1,'H':2})[x];}},'street'));' – 2012-03-08 13:40:13

回答

5

Array.sort()方法接受分类功能,可以让你实现自己的排序。

data.sort(function (a, b) { 
    // Specify the priorities of the types here. Because they're all one character 
    // in length, we can do simply as a string. If you start having more advanced 
    // types (multiple chars etc), you'll need to change this to an array. 
    var order = 'SCH'; 
    var typeA = order.indexOf(a.type); 
    var typeB = order.indexOf(b.type); 

    // We only need to look at the year if the type is the same 
    if (typeA == typeB) { 
     if (a.year < b.year) { 
      return -1; 
     } else if (a.year == b.year) { 
      return 0; 
     } else { 
      return 1; 
     } 

    // Otherwise we inspect by type 
    } else { 
     return typeA - typeB; 
    } 
}); 

Array.sort()预计0要返回如果a == b,< 0如果a < b和> 0,如果a > b

你可以在这里看到这个工作; http://jsfiddle.net/32zPu/

+1

This works。我可以想出一种按特殊顺序排序的方法。谢谢 – 2012-03-08 13:30:47

+0

S,C和H不是按字母顺序排列:P – hugomg 2012-03-08 13:35:25

+1

@missingno:从OP的代码:*应订购S,C,然后H. *。 – 2012-03-08 13:38:35

2

我upvoted马特的答案,但想添加一个稍微不同的方法从中可以值工作不仅仅是单个字符和一个短一点的方式来比较年份值的类型越来越排序顺序:

data.sort(function(a, b) { 
    var order = {"S": 1,"C": 2,"H": 3}, typeA, typeB; 
    if (a.type != b.type) { 
     typeA = order[a.type] || -1; 
     typeB = order[b.type] || -1; 
     return(typeA - typeB); 
    } else { 
     return(a.year.localeCompare(b.year)); 
    } 
}); 

工作演示:http://jsfiddle.net/jfriend00/X3rSj/

+0

“localeCompare”为+1 ...我以前从未遇到过! – Matt 2012-03-08 14:55:27

0

您可以通过自定义函数的数组排序方法,可以让你定义项目的排序方式。像这样的东西应该工作(您未排序的数据将在“数据” VAR):?如何排序多个字段对象的数组]

function sortFunc (item1, item2) { 
    var sortOrder = 'SCH'; 
    if (item1.type != item2.type) 
    { 
    return sortOrder.indexOf(item1.type) - sortOrder.indexOf(item2.type); 
    } 
    else 
    { 
    return item1.year.localeCompare(item2.year); 
    } 
} 

var sortedData = data.sort(sortFunc); 
相关问题