[英]Javascript sorting caption array the same way as according data array
I have a sorting problem in javascript, I need to sort an array and sort the captions (saved in another array) in the same order (descending), how can I sort them the same way? 我在javascript中有一个排序问题,我需要对数组进行排序并以相同的顺序(降序)对字幕(保存在另一个数组中)进行排序,我该如何以相同的方式对其进行排序?
For the clarity of my post I will reduce it to a basic example: 为了清楚起见,我将其简化为一个基本示例:
var arr = Array(9, 5, 11, 2, 3);
var arrCaptions = Array("some text","another bit of text","three", "four?", "maybe five?");
Now I want to run a kind of sort mechanism that sorts the arrCaptions array the same way as the arr array, so as result you would get this: 现在,我想运行一种排序机制,以与arr数组相同的方式对arrCaptions数组进行排序,因此您将获得以下结果:
var arrResult = Array(11, 9, 5, 3, 2);
var arrCaptionsResult = Array("three", "some text" ,"another bit of text", "maybe five?", "four?");
What I have tried so far doesn't work at all: 到目前为止,我尝试过的一切根本不起作用:
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]);
}
Bundle them together in an object. 将它们捆绑在一个对象中。
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.
});
The result is: 结果是:
[{
"id": 2,
"text": "text 23"
}, {
"id": 5,
"text": "text world"
}, {
"id": 9,
"text": "text hello"
}, {
"id": 11,
"text": "text test"
}]
How about combining them into one array? 如何将它们组合成一个数组? Then you can sort this array based on the value of the numbers, and the captions get sorted in tandem:
然后,您可以根据数字的值对该数组进行排序,并且标题将一前一后地排序:
//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);
Here is a demonstration: http://jsfiddle.net/cFDww/ 这是一个演示: http : //jsfiddle.net/cFDww/
Here is your modified code: 这是修改后的代码:
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.