Javascript排序标题数组的方式与根据数据数组相同

时间:2012-12-17 15:50:56

标签: javascript arrays string sorting

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

3 个答案:

答案 0 :(得分: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"
}]

答案 1 :(得分: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/

答案 2 :(得分: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