2

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

3 回答 3

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"
}]
于 2012-12-17T15:55:04.893 回答
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/

于 2012-12-17T15:56:31.460 回答
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);

看到它工作

于 2012-12-17T17:19:39.633 回答