2012-03-08 4 views
0

나는 하나의 값 (텍스트 또는 숫자)과 두 개의 숫자 (연도와 무언가의 수)로 배열을 정렬하는 방법에 대한 질문과 답을 보았다.자바 스크립트에서 두 이름으로 배열을 정렬하는 방법?

한 문자열을 오름차순으로 정렬하고 다른 문자열을 특별한 순서로 정렬하려면 어떻게합니까?

여기 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/ 질문/6913512/how-to-sort-of-objects-by-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];}}, 'street')) ' –

답변

5

과 같아야 하나의 배열

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 
} 

에서 객체와 예상 최종 결과입니다.

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 IF 및> 0 a > b 경우.

여기서 알 수 있습니다. 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 for'localeCompare' ... 전에는 그걸 보지 못했습니다! – Matt

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); 
관련 문제