2 Dimensional Array Sort Javascript

6 min read Jun 22, 2024
2 Dimensional Array Sort Javascript

Sorting 2 Dimensional Arrays in JavaScript

Sorting two-dimensional arrays in JavaScript can be a bit trickier than sorting one-dimensional arrays because you need to consider which dimension to sort on and how to compare elements within that dimension. Here's a breakdown of common approaches and code examples:

1. Sorting by a Specific Column

The most common scenario is sorting by a specific column. This involves comparing elements in that column of each row and rearranging the rows accordingly. You can achieve this using the built-in sort() method in JavaScript, along with a custom comparison function.

const myArray = [
  [1, 'apple', 10],
  [3, 'banana', 5],
  [2, 'cherry', 8],
];

// Sort by the first column (index 0) in ascending order
myArray.sort((a, b) => {
  return a[0] - b[0]; // Compare values in the first column
});

console.log(myArray); // Output: [[1, 'apple', 10], [2, 'cherry', 8], [3, 'banana', 5]] 

// Sort by the second column (index 1) in descending order
myArray.sort((a, b) => {
  return b[1].localeCompare(a[1]); // Compare values in the second column
});

console.log(myArray); // Output: [[3, 'banana', 5], [2, 'cherry', 8], [1, 'apple', 10]]

Explanation:

  • myArray.sort((a, b) => ...): This line calls the built-in sort() method on the array, providing a comparison function as an argument.
  • return a[0] - b[0];: This compares the values in the first column (index 0) of the two rows being compared (a and b). The result determines the sorting order:
    • Negative value: a comes before b
    • Zero: a and b stay in their relative order
    • Positive value: b comes before a
  • To sort in descending order, simply swap the positions of a and b within the comparison function.
  • b[1].localeCompare(a[1]): This line uses the localeCompare() method to compare strings in the second column. It's important for string comparisons to ensure correct alphabetical order based on the locale.

2. Sorting by Multiple Columns

To sort by multiple columns, you can chain comparison checks within the sort function. If the values in the first column are equal, you compare the values in the second column, and so on.

const myArray = [
  [1, 'apple', 10],
  [3, 'banana', 5],
  [2, 'cherry', 8],
  [1, 'grape', 2],
];

// Sort by the first column (ascending) and then the second column (descending)
myArray.sort((a, b) => {
  if (a[0] === b[0]) {
    return b[1].localeCompare(a[1]); // If first column is equal, compare second column
  } else {
    return a[0] - b[0]; // Otherwise, compare the first column
  }
});

console.log(myArray); // Output: [[1, 'grape', 2], [1, 'apple', 10], [2, 'cherry', 8], [3, 'banana', 5]]

3. Sorting by Custom Logic

You might need to sort based on more complex criteria, such as applying custom functions or calculations to the data. In this case, you can write your own comparison logic within the sort() function.

const myArray = [
  [1, 'apple', 10],
  [3, 'banana', 5],
  [2, 'cherry', 8],
];

// Sort by the sum of the first and third columns
myArray.sort((a, b) => {
  const sumA = a[0] + a[2];
  const sumB = b[0] + b[2];
  return sumA - sumB; // Compare the sums
});

console.log(myArray); // Output: [[3, 'banana', 5], [2, 'cherry', 8], [1, 'apple', 10]]

Remember: Sorting 2D arrays involves more customization and careful consideration compared to sorting one-dimensional arrays.

  • Understand your sorting criteria: What column(s) do you want to sort by?
  • Consider the data types in the columns: Are you sorting numbers, strings, or objects?
  • Write clear and efficient comparison functions.

These examples provide a good starting point for sorting 2D arrays in JavaScript. Feel free to adapt and extend the provided code to suit your specific needs and scenarios.

Latest Posts