2012-12-17 22 views
2

我有一個排序問題在JavaScript中,我需要排序一個數組和排序字幕(保存在另一個數組中)以相同的順序(降序),我怎麼排序他們以同樣的方式?Javascript排序標題數組與相同的數據排列方式

對於帖子的清晰,我將其降低到一個基本的例子:

var arr = Array(9, 5, 11, 2, 3); 
var arrCaptions = Array("some text","another bit of text","three", "four?", "maybe five?"); 

現在我想運行的一種排序機制,排序arrCaptions陣列相同的方式ARR陣列,這樣的結果,你會得到這樣的:

var arrResult = Array(11, 9, 5, 3, 2); 
var arrCaptionsResult = Array("three", "some text" ,"another bit of text", "maybe five?", "four?"); 

我至今嘗試過沒有在所有的工作:

var numlist = Array(9, 5, 11, 2, 3); 
var list = Array("four?","maybe five?","another bit of text","some text","three"); 

var resultnumlist = Array(); 
var resultlist = Array(); 

resultnumlist[0] = numlist[0]; 
resultlist[0] = list[0]; 

for (i = 0; i < list.length; i++) { 
    var i2 = list.length - 1; 
    while (numlist[i] < resultnumlist[i2]) { 
     i2--; 
    } 
    resultnumlist.splice(i2 - 1,0,numlist[i]); 
    resultlist.splice(i2 - 1,0,list[i]); 
} 
+1

雖然,您已經選擇了您的答案,但如果您可以解釋您嘗試構建的邏輯,我可以幫助修復您的代碼。你只是想在每次運行中找到最低的數字,然後將它插入到結果數組中?如果是這樣,請檢查:http://jsbin.com/awaveb/3/watch – closure

+0

是的,這就是我試過的,我檢查了你的代碼,這實際上是我想要的。 :)雖然它是一種錯誤的方式,但找不到我自己的錯誤... – JohannesB

+0

我的邏輯如下:從最後一個元素開始(如果算法運行良好,這將是最低的),循環遍歷結果數組直到電流的值大於結果數組索引,然後記住該索引的數量。然後,我會在該索引處插入新元素的值,就像我會處理該值的標題一樣。理論上,結果將是一個完美排序的數組:P – JohannesB

回答

1

下面是修改後的代碼:

var numlist = Array(9, 5, 11, 2, 3); 
    var list = Array("nine?","maybe five?","another bit of 11","some 2","three"); 

    var resultnumlist = new Array(); 
    var resultlist = new Array(); 

    for (i = 0; i < list.length; i++) { 
     var i2 = resultnumlist.length - 1; 
     while ((numlist[i] < resultnumlist[i2]) && (i2 >= 0)) { 
      i2--; 
     } 
     i2++; 
     resultnumlist.splice(i2, 0, numlist[i]); 
     resultlist.splice(i2, 0, list[i]); 
    } 
    console.log(resultlist); 
    console.log(resultnumlist); 

See it working

+0

@ user1493235這裏是你的代碼編輯遵循你的邏輯。 – closure

+0

我的錯誤是在i2 ++和while循環中,現在我發現我的錯誤,如果我認爲它的邏輯與示例。所以現在我不僅得到了一個解決方案,我學到了一些新東西,並且知道我的錯,這對我更重要:)非常感謝! – JohannesB

2

將它們一起捆綁在一個對象中。

var stuff = [{ 
    id: 9, 
    text: "text hello" 
}, { 
    id: 5, 
    text: "text world" 
}, { 
    id: 11, 
    text: "text test" 
}, { 
    id: 2, 
    text: "text 23" 
}]; 

stuff.sort(function(a, b) { 
    return a.id - b.id; //Objects are sorted ascending, by id. 
}); 

結果是:

[{ 
    "id": 2, 
    "text": "text 23" 
}, { 
    "id": 5, 
    "text": "text world" 
}, { 
    "id": 9, 
    "text": "text hello" 
}, { 
    "id": 11, 
    "text": "text test" 
}] 
2

如何將它們組合成一個陣列?然後你就可以進行排序基於數字的值這個數組,和字幕得到串聯排序:

//Your arrays 
var arr = [9, 5, 11, 2, 3]; 
var arrCaptions = ["some text", "another bit of text", "three", "four?", "maybe five?"]; 

//The composite array 
var composite = arr.map(function(v, i) { 
    return { 
     rank: v, 
     caption: arrCaptions[i] 
    }; 
}); 

//Sort this array 
composite.sort(function(a, b) { 
    return a.rank - b.rank; 
}); 

console.log(composite); 

這裏是一個演示:http://jsfiddle.net/cFDww/