Talked Asked: 2020-12-21 08:27:54 +0800 CST 2020-12-21 08:27:54 +0800 CST 2020-12-21 08:27:54 +0800 CST 如何使用javascript对多维数组进行排序? 772 我有这个多维数组,我正在尝试使用索引“名称”进行排序,我尝试了 sort() 函数,但它不起作用。 我也试过这个,但它也不起作用,我试图排序的数组称为结果。 var x = $scope.result.sort(function(a,b){return a[0][1] > b[0][1] ? 1 : -1;}); 是否可以按照名称的字母顺序对其进行排序?即首先是“aaa”,然后是“bbbb”,依此类推。 javascript 2 Answers Voted Best Answer Orlando De La Rosa 2020-12-21T08:59:46+08:002020-12-21T08:59:46+08:00 您可以尝试: objs.sort(function(a, b){ return a.nombre > b.nombre ? 1 : b.nombre > a.nombre ? -1 : 0 }); 或使用箭头函数表达式: objs.sort((a, b) => a.first_nom > b.first_nom ? 1 : b.first_nom > a.first_nom ? -1 : 0); 您还可以使用以下功能localCompare: objs.sort((a, b) => a.nombre.localeCompare(b.nombre)); Angel Oropeza 2020-12-21T11:52:48+08:002020-12-21T11:52:48+08:00 假设您是以下形式的数组数组: var array = [ [ { id: 0, nombre: "ccc" }, { id: 1, nombre: "bbb" }, { id: 2, nombre: "ddd" }, { id: 3, nombre: "aaa" } ], [ { id: 4, nombre: "hhh" }, { id: 5, nombre: "eee" }, { id: 6, nombre: "fff" }, { id: 7, nombre: "ggg" } ] ]; 您可以使用该函数遍历第一个元素,forEach然后使用该函数sort()对它们进行排序。 var newArray = []; array.forEach(elemento => { newArray.push(elemento.sort((a, b) => a.nombre < b.nombre ? -1 : a.nombre > b.nombre ? 1 : 0)); }); console.log(newArray); 这里是完整的例子: var array = [ [ { id: 0, nombre: "ccc" }, { id: 1, nombre: "bbb" }, { id: 2, nombre: "ddd" }, { id: 3, nombre: "aaa" } ], [ { id: 4, nombre: "hhh" }, { id: 5, nombre: "eee" }, { id: 6, nombre: "fff" }, { id: 7, nombre: "ggg" } ] ]; var newArray = []; array.forEach(elemento => { newArray.push(elemento.sort((a, b) => a.nombre < b.nombre ? -1 : a.nombre > b.nombre ? 1 : 0)); }); console.log(newArray); 参考 种类() forEach()
您可以尝试:
或使用箭头函数表达式:
您还可以使用以下功能
localCompare
:假设您是以下形式的数组数组:
您可以使用该函数遍历第一个元素,
forEach
然后使用该函数sort()
对它们进行排序。这里是完整的例子:
参考