Javascript 二维数组排序
在下面的示例中,如何对二维数组进行排序Javascript 二维数组排序,javascript,arrays,sorting,Javascript,Arrays,Sorting,在下面的示例中,如何对二维数组进行排序 var films = [ ["action,sci-fi", "Star Wars", "description..."], ["comedy,adventure,sci-fi", "Back to the future", "description..."], ["drama", "The Green Mile",
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..."],
];
如果按索引位置1中的字符串排序,则:
films.sort(function(item1, item2){
if (item1[1] > item2[1])
return 1;
if (item1[1] < item2[1])
return -1;
return 0;
});
films.sort(功能(项目1、项目2){
如果(项目1[1]>项目2[1])
返回1;
如果(第1项[1]<第2项[1])
返回-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
var胶片=[
{名称:“星球大战”},
{name:“回到未来”},
{名称:“深红峰”}
]; // 原始数组
var sortByName=[];//要排序的新数组
对于(i=0;i在提供的示例中排序为?FWIW,那些以“The”开头的影片应格式化为“Green Mile,The”等。如果有很长的列表,则便于搜索。有很多以“The”开头的影片:为什么在一个数组中有数组,而在一个数组中有一个键值对的对象呢?我能想到一些同名的电影(大多数翻拍的电影)不适合这种结构。@Andy OP现在也在做同样的事情。我看不出有什么区别。同名电影的列表与对象相同。比较函数应返回-1
、0
或1
,而不是true
或false
。我将删除否则
。只需满足这两个条件,如果两个条件都不满足,则返回0。