如何在 TypeScript 中排序二維陣列?


在 TypeScript 中,二維陣列是一個數組的陣列,其中每個內部陣列表示二維陣列的一行。您可以使用方括號表示法訪問陣列的單個元素,行索引和列索引用逗號分隔。一維陣列可以儲存任何資料型別的值,例如字串、數字、物件等。

要對 TypeScript 中的二維陣列進行排序,您可以使用sort()方法以及自定義比較函式。sort()方法將比較函式作為可選引數,比較函式應接收兩個引數 a 和 b,它們分別表示要比較的兩個元素。如果 a 在 b 之前,比較函式應返回負數;如果 a 在 b 之後,則返回正數;如果 a 和 b 相同,則返回 0。

開發過程中經常需要根據特定條件對二維陣列的值進行排序。因此,我們將在下面學習如何按行和按列對二維陣列進行排序。

使用 array.sort() 方法按行排序二維陣列

通常,我們使用 Array 類的 sort() 方法對陣列進行排序,而不是建立自定義演算法(如歸併排序或快速排序)。sort() 方法的實現具有比其他排序演算法更低的時空複雜度。

語法

要按行排序二維陣列,我們必須將包含排序條件的回撥函式作為 sort() 方法的引數傳遞。使用者可以按照以下語法按行排序二維陣列。

let arr: Array<Array<number>> = [];
for (let i = 0; i < arr.length; i++) {
   arr[i].sort( (a, b) => {
      if (first === second) {
         return 0;
      } else {
         if (first < second) {
            return -1;
         }
         return 1;
      }
   });
}

在上述語法中,我們遍歷陣列的每一行,並分別對每一行進行排序。在 array.sort() 方法中,傳遞了回撥函式,該函式返回 0、-1 和 1 以相應地對數字進行排序。

演算法

步驟 1 - 建立名為“arr”的數字型別陣列。

步驟 2 - 遍歷矩陣的每一行,分別對每一行進行排序。

步驟 3 - 對每一行呼叫 sort() 方法。

步驟 4 - 將回調函式作為 sort() 方法的引數傳遞,該函式將行的兩個值作為引數。

步驟 5 - 在比較兩個引數值以按升序或降序對它們進行排序後,從回撥函式返回零、正數和負數。

示例

在下面的示例中,我們建立了數字的二維陣列並向其中添加了一些數字。我們使用 sort() 方法對每一行進行排序,回撥函式根據其引數值的相等性返回 0、-1 和 1。

//  Creating the array of numbers and inserting the values
let arr: Array<Array<number>> = [];
arr.push([0, 4, 67, 32, 21, 11]);
arr.push([56, 43, 32, 21, 45, 56]);
arr.push([8, 98, 78, 41, 1, 2]);
arr.push([3, 87, 8, 5, 4, 21]);
// Sort every row seprately
for (let i = 0; i < arr.length; i++) {
   arr[i].sort(sort_callback);
}
// Callback function for the sort method, which returns the numbers
function sort_callback(first: number, second: number): number {
   // If both number is equal, return 0. It means, it will not change position of numbers
   if (first === second) {
      return 0;
   } else {
      // If first number is smaller, return -1, It will also not swap numbers
      if (first < second) {
         return -1;
      }
      //  If first number is larger than second number, return 1 to swap both numbers.
      return 1;
   }
}
// Print the array
console.log("Array after sorting row-wise:");
console.log(" ");
console.log(arr);

編譯後,它將生成以下 JavaScript 程式碼 -

//  Creating the array of numbers and inserting the values
var arr = [];
arr.push([0, 4, 67, 32, 21, 11]);
arr.push([56, 43, 32, 21, 45, 56]);
arr.push([8, 98, 78, 41, 1, 2]);
arr.push([3, 87, 8, 5, 4, 21]);
// Sort every row seprately
for (var i = 0; i < arr.length; i++) {
   arr[i].sort(sort_callback);
}
// Callback function for the sort method, which returns the numbers
function sort_callback(first, second) {
   // If both number is equal, return 0. It means, it will not change position of numbers
   if (first === second) {
      return 0;
   }
   else {
      // If first number is smaller, return -1, It will also not swap numbers
      if (first < second) {
         return -1;
      }
      //  If first number is larger than second number, return 1 to swap both numbers.
      return 1;
   }
}
// Print the array
console.log("Array after sorting row-wise:");
console.log(" ");
console.log(arr);

輸出

以上程式碼將產生以下輸出 -

Array after sorting row-wise:
[ [ 0, 4, 11, 21, 32, 67 ],
   [ 21, 32, 43, 45, 56, 56 ],
   [ 1, 2, 8, 41, 78, 98 ],
   [ 3, 4, 5, 8, 21, 87 ] ]

在上述輸出中,使用者可以觀察到所有行都是分別排序的。

使用 array.sort() 方法按列排序二維陣列

在上一部分中,我們學習瞭如何按行排序陣列。現在,我們將學習如何按列排序陣列。按列排序意味著我們將根據任何特定陣列列對二維陣列的行進行排序或交換。

語法

使用者可以按照以下語法按列排序二維陣列。

let arr: Array<Array<number>> = [];
arr.sort( (
   firstRow: Array<number>,
   secondRow: Array<number>
): number => {
   if (firstRow[2] === secondRow[2]) {
      return 0;
   } else {
      if (firstRow[2] < secondRow[2]) {
         return -1;
      }
      return 1;
   }
}

在上述語法中,我們使用了 array.sort() 方法並將箭頭函式作為回撥傳遞。箭頭函式根據特定列的值返回正值和負值,sort() 方法相應地對陣列進行排序。

示例

根據第 3 列排序陣列

下面的示例中使用 sort() 方法按列對二維陣列進行排序。sort() 方法的回撥函式根據作為回撥函式引數傳遞的任何兩行的第三個元素的比較返回零、正數和負數。

//  Creating the array and initialize it with values
let arr: Array<Array<number>> = [
   [0, 4, 67, 32, 21, 11],
   [56, 43, 32, 21, 45, 56],
   [8, 98, 78, 41, 1, 2],
   [3, 87, 8, 5, 4, 21],
];
arr.sort(sort_columnWise);

// Callback function to sort array according to the third column.
// If callback function will return 1, sort() method swap the row, Otherwise not.
function sort_columnWise(
   firstRow: Array<number>,
   secondRow: Array<number>
): number {
   if (firstRow[2] === secondRow[2]) {
      return 0;
   } else {
      if (firstRow[2] < secondRow[2]) {
         return -1;
      }

      return 1;
   }
}
// Print the array
console.log("Array after sorting according 3rd column:");
console.log(" ");
console.log(arr);

編譯後,它將生成以下 JavaScript 程式碼 -

//  Creating the array and initialize it with values
var arr = [
   [0, 4, 67, 32, 21, 11],
   [56, 43, 32, 21, 45, 56],
   [8, 98, 78, 41, 1, 2],
   [3, 87, 8, 5, 4, 21],
];
arr.sort(sort_columnWise);
// Callback function to sort array according to the third column.
// If callback function will return 1, sort() method swap the row, Otherwise not.
function sort_columnWise(firstRow, secondRow) {
   if (firstRow[2] === secondRow[2]) {
      return 0;
   }
   else {
      if (firstRow[2] < secondRow[2]) {
         return -1;
      }
      return 1;
   }
}
// Print the array
console.log("Array after sorting according 3rd column:");
console.log(" ");
console.log(arr);

輸出

以上程式碼將產生以下輸出 -

Array after sorting according 3rd column:
[ [ 3, 87, 8, 5, 4, 21 ],
   [ 56, 43, 32, 21, 45, 56 ],
   [ 0, 4, 67, 32, 21, 11 ],
   [ 8, 98, 78, 41, 1, 2 ] ]

在輸出中,使用者可以觀察到所有行都是根據**第三列**的值排序的。

示例

在下面的示例中,我們建立了一個物件陣列,其中包含姓名和加入年份作為員工資料。我們對陣列使用 sort() 方法,並根據作為回撥函式引數傳遞的第一和第二個物件的年份之間的差異對所有物件進行排序。

let employee_Data: Array<{ name: string; joinedYear: number }> = [
   { name: "Shubham", joinedYear: 2019 },
   { name: "Jems", joinedYear: 2021 },
   { name: "Bond", joinedYear: 2022 },
   { name: "Akshay", joinedYear: 2017 },
   { name: "sulabh", joinedYear: 2012 },
];
// Sort array of objects according to joinedyear property of the object
employee_Data.sort((first, second) => {
   // return 0, positive, or negative value according to difference of the year
   // If difference is positive, sort() method will swap the objects, otherwise not.
   // If users want to sort array in the decreasing order, just return second.joinedYear - first.joinedYear
   return first.joinedYear - second.joinedYear;
});

// Print the array
console.log("Array after sorting according joindedYear:");
console.log(" ");
console.log(employee_Data);

編譯後,它將生成以下 JavaScript 程式碼 -

var employee_Data = [
   { name: "Shubham", joinedYear: 2019 },
   { name: "Jems", joinedYear: 2021 },
   { name: "Bond", joinedYear: 2022 },
   { name: "Akshay", joinedYear: 2017 },
   { name: "sulabh", joinedYear: 2012 },
];
// Sort array of objects according to joinedyear property of the object
employee_Data.sort(function (first, second) {
   // return 0, positive, or negative value according to difference of the year
   // If difference is positive, sort() method will swap the objects, otherwise not.
   // If users want to sort array in the decreasing order, just return second.joinedYear - first.joinedYear
   return first.joinedYear - second.joinedYear;
});
// Print the array
console.log("Array after sorting according joindedYear:");
console.log(" ");
console.log(employee_Data);

輸出

以上程式碼將產生以下輸出 -

Array after sorting according joindedYear:
[ { name: 'sulabh', joinedYear: 2012 },
   { name: 'Akshay', joinedYear: 2017 },
   { name: 'Shubham', joinedYear: 2019 },
   { name: 'Jems', joinedYear: 2021 },
   { name: 'Bond', joinedYear: 2022 } ]

更新於:2022-12-19

4K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告