如何在以下示例中对二维数组进行排序
var films = [
["action,sci-fi", "Star Wars", "description..."],
["comedy,adventure,sci-fi", "Back to the future", "description..."],
["drama", "The Green Mile", "description..."],
["drama,comedy", "Forrest Gump", "description..."],
["fantasy,adventure", "The Lord of the Rings", "description..."],
];
排序:
var films = [
["comedy,adventure,sci-fi", "Back to the future", "description..."],
["drama,comedy", "Forrest Gump", "description..."],
["action,sci-fi", "Star Wars", "description..."],
["drama", "The Green Mile", "description..."],
["fantasy,adventure", "The Lord of the Rings", "description..."],
];
答案 0 :(得分:3)
如果您按索引位置1中的字符串排序,则:
films.sort(function(item1, item2){
if (item1[1] > item2[1])
return 1;
if (item1[1] < item2[1])
return -1;
return 0;
});
答案 1 :(得分:0)
您还可以更改数组的结构并创建对象而不是数组。我使用纯javascript的简化版本。
var films = [
{name: "Star Wars"},
{name: "Back to the Future"},
{name: "Crimsons Peak"}
]; // original array
var sortByName = []; // new array to sort by
for(i=0; i<films.length; i++) {
sortByName.push(films[i].name);
}
console.log(sortByName); // unordered
console.log(sortByName.sort()); // ordered