2012-03-08 9 views
0

私は1つの値(テキストまたは数値)と2つの数値(年と何かの数)で配列を並べ替える方法について質問と回答を見てきました。javascriptで2つの名前で配列をソートする方法は?

1つの文字列を昇順に並べ替えたり、別の文字列を特別な順序で並べ替えるにはどうすればよいですか?

はここArray.sort()方法は、あなた自身をソート実装することができますソート機能を、受け入れるこの

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/ [複数のフィールドでオブジェクトの配列をソートする方法?]:この動作するはずです(あなたのソートされていないデータは「データ」VARにあるであろう)のようなもの質問/ 6913512/how-to-sort-of-multiple-fieldsによるオブジェクトの配列) –

+0

ちょうど確認する:私の答えで関数を使用することができ、 '型'戻る'S'の場合は '0 '、' C'の場合は '1'、 'H 'の場合は' 2'のように、各文字の番号。data.sort(sort_by({name: 'type'、primer:function( x){return({'S':0、 'C':1、 'H':2})[x];}}、 ' –

答えて

5

のようになります。1列

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 
} 

からオブジェクトおよび予想される最終的な結果です。 a < bと> 0であれば

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()a == b場合は0が返されることを期待し、場合。

これはここで動作します。 http://jsfiddle.net/32zPu/

+1

これは機能します。私は特別な順序でタイプ別にソートする方法を考えることができます。ありがとうございます –

+0

S、C、Hはアルファベット順ではありません:P – hugomg

+1

@missingno:OPのコードから:* S、C、Hの順に並べる必要があります。 –

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

+1は 'localeCompare'のために...私はこれまでに遭遇したことはありません! – Matt

0

をあなたが項目の並べ替え方法を定義することができます配列のソート方法にカスタム関数を渡すことができます。

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); 
関連する問題