如何按子数组中的第一项对数组进行排序 - JavaScript?
假设我们有以下数组 −
var studentDetails = [ [89, "John"], [78, "John"], [94, "John"], [47, "John"], [33, "John"] ];
而且我们需要根据第一个项对数组进行排序,即 89、78、94 等。为此,请使用 sort()。
示例
以下是代码 −
var studentDetails = [ [89, "John"], [78, "John"], [94, "John"], [47, "John"], [33, "John"] ]; studentDetails.sort((first, second) => second[0] - first[0]) console.log(studentDetails);
要运行上述程序,您需要使用以下命令 −
node fileName.js.
在此,我的文件名是 demo293.js。
输出
这将产生以下控制台输出 −
PS C:\Users\Amit\javascript-code> node demo293.js [ [ 94, 'John' ], [ 89, 'John' ], [ 78, 'John' ], [ 47, 'John' ], [ 33, 'John' ] ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP