簡體   English   中英

JavaScript排序標題數組與根據數據數組的方式相同

[英]Javascript sorting caption array the same way as according data array

我在javascript中有一個排序問題,我需要對數組進行排序並以相同的順序(降序)對字幕(保存在另一個數組中)進行排序,我該如何以相同的方式對其進行排序?

為了清楚起見,我將其簡化為一個基本示例:

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

現在,我想運行一種排序機制,以與arr數組相同的方式對arrCaptions數組進行排序,因此您將獲得以下結果:

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]);
}

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

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"
}]

如何將它們組合成一個數組? 然后,您可以根據數字的值對該數組進行排序,並且標題將一前一后地排序:

//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/

這是修改后的代碼:

  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);

看到它正常工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM