Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Sắp xếp mảng theo mục đầu tiên trong mảng con - JavaScript

Giả sử chúng ta có mảng sau:

var studentDetails = [ 
  [89, "John"], 
  [78, "John"], 
  [94, "John"], 
  [47, "John"], 
  [33, "John"] 
];

Cần sắp xếp mảng dựa trên mục đầu tiên (89, 78, 94...). Sử dụng sort().

Ví dụ

Mã minh họa:

var studentDetails = [ 
  [89, "John"], 
  [78, "John"], 
  [94, "John"], 
  [47, "John"], 
  [33, "John"] 
]; 
studentDetails.sort((first, second) => second[0] - first[0]); 
console.log(studentDetails);

Để chạy chương trình, sử dụng lệnh:

node tenFile.js

Tên file ở đây là demo293.js.

Kết quả

Đầu ra trên console (sắp xếp giảm dần theo số):

PS C:\Users\Amit\javascript-code> node demo293.js
[ [ 94, 'John' ], [ 89, 'John' ], [ 78, 'John' ], [ 47, 'John' ], [ 33, 'John' ] ]