How to sort a 2D array in TypeScript?


In TypeScript, a 2D array is an array of arrays, where each inner array represents a row of the 2D array. You can access individual elements of the array using bracket notation, with the row and column indices separated by a comma. A single-dimensional array can store values of any data type, such as string, number, objects, etc.

To sort a 2D array in TypeScript, you can use the sort() method along with a custom compare function. The sort() method takes the compare function as an optional argument, and the compare function should take two arguments, a and b, which represent the two elements being compared. The compare function should return a negative number if a comes before b, a positive number if a comes after b, and 0 if a and b are the same.

Development processes often require sorting the values of a 2D array based on a certain condition. So, we will learn to sort the 2D array row-wise and column-wise below.

Sorting a 2D array row-wise using the array.sort() method

Generally, we use the sort() method of the Array class to sort the array rather than creating a custom algorithm such as merge sort or quick sort. The sort() method is implemented to have the lowest time and space complexity than other sorting algorithms.

Syntax

To sort the 2D array row-wise, we have to pass the callback function containing the sorting condition as a parameter of the sort() method. Users can follow the syntax below to sort the 2D array row-wise.

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;
      }
   });
}

In the above syntax, we are iterating through every row of the array and sorting every row separately. In the array.sort() method, passed the callback function, which returns 0,-1, and 1 to sort the numbers accordingly.

Algorithm

Step 1 − Create the array called ‘arr’ of type numbers.

Step 2 − Iterate through every row of the matrix to sort every row separately.

Step 3 − Call the sort() method for every row.

Step 4 − Pass the callback function as a parameter of the sort() method, which takes the two values of the row as a parameter.

Step 5 − Return the zero, positive, and negative values from the callback function after comparing the two parameter values to sort them in increasing or decreasing order.

Example

In the below example, we have created the two-dimensional array of numbers and pushed some numbers into that. We used the sort() method to sort every row, and the callback function returns 0, -1, and 1 based on the equality of its parameter values.

//  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);

On compiling, it will generate the following JavaScript code −

//  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);

Output

The above code will produce the following output −

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 ] ]

In the above output, users can observe that all rows are sorted separately.

Sorting a 2D array Column-wise using the array.sort() method

In the above part, we learned to sort the array row-wise. Now, we will learn to sort the array column-wise. The column-wise sorting means that we will sort or swap the rows of the 2D array based on any particular array column.

Syntax

Users can follow the syntax below to sort the 2D array column-wise.

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;
   }
}

In the above syntax, we used the array.sort() method and passed the arrow function as a callback. The arrow function returns the positive and negative values based on the value of the particular column and the sort() method sorts the array accordingly.

Example

Sorting the array according to 3rd column

The sort() method is used in the example below to sort the two dimension array column-wise. The callback function of the sort() method returns the zero, positive, and negative values based on the comparison of the third element of any two rows passed as parameters of the callback function.

//  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);

On compiling, it will generate the following JavaScript code −

//  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);

Output

The above code will produce the following output −

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 ] ]

In the output, users can observe that all rows are sorted according to the value of the third column.

Example

In the example below, we have created an array of objects which contains the name and joined year as employee data. We use the sort() method for the array and sorting all objects based on the difference between the year of the first and second objects passed as a callback function parameter.

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);

On compiling, it will generate the following JavaScript code −

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);

Output

The above code will produce the following output −

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 } ]

Updated on: 19-Dec-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements