How to Sort Multidimensional Array in JavaScript

Migel Hewage Nimesha Feb 02, 2024
  1. Sort a Single Dimensional Array in JavaScript
  2. Sort a Multidimensional Array or N-D Array in JavaScript
  3. Conclusion
How to Sort Multidimensional Array in JavaScript

Sorting is a method for putting items in ascending or descending order. The sorting of elements is done by comparison with another item or element.

Sort a Single Dimensional Array in JavaScript

To demonstrate this, let us consider a single-dimensional array as [2,78,4,10,3,59,6] to perform sorting.

Code:

// single-dimensional array
const array = [2, 78, 4, 10, 3, 59, 6];

// sorting in increasing order
const in_array = array.sort((a, b) => {
  return a - b;
})

console.log(in_array);

// sorting in decreasing order
const de_array = array.sort((a, b) => {
  return b - a;
})

console.log(de_array);

The expected output after sorting is as follows:

JavaScript Sort Array - Output

Here, the elements are sorted in increasing order, which means the elements are arranged in ascending order. The elements of the array are also sorted in decreasing order, which means the elements are arranged in descending order.

We will use the arrow function in JavaScript to perform this sorting.

Note: The Arrow function is one of the functions introduced in the ES6 version of JavaScript. It lets you create functions more cleanly compared to regular functions.

For example, if this is the original function:

let testFunction = function(a, b) {
  return a * b;
}

This function can be written in a simpler form as follows using the arrow function:

let testFunction = (a, b) => a * b;

Sort a Multidimensional Array or N-D Array in JavaScript

Multidimensional arrays can be sorted using JavaScript’s array sort() method. Here, multidimensional arrays are sorted based on column index numbers.

Let us demonstrate sorting by taking a multidimensional array as [[0,1,2,0,0], [3,0,0,2,0], [2,0,0,4,6], [0,3,4,0,5], [0,0,3,5,0]].

Code:

// multidimensional array
const multidimensional_array = [
  [0, 1, 2, 0, 0], [3, 0, 0, 2, 0], [2, 0, 0, 4, 6], [0, 3, 4, 0, 5],
  [0, 0, 3, 5, 0]
];

// sorting multidimensional array

multidimensional_array.sort((a, b) => {
  // performing sorting based on 2nd, and 3rd columns of the matrix
  return a[2] - b[2];
})

console.log(multidimensional_array);

The output received after sorting is as follows:

JavaScript Sort Multidimensional Array - Output 1

We can apply different methods or techniques for sorting multidimensional arrays as necessary.

Let’s say we have the following array of arrays.

const array = [['M', 'B', 'M', 'Z', 'B', 'B'], ['B', 'M', 'M', 'B', 'B', 'Z']];

We must create a JavaScript function that accepts one array of this type. The function should use the rules below to internally sort each supplied array’s subarray.

  • If the elements are neither M nor B, they should stay in their position.
  • If the element is either M or B, they should be sorted alphabetically.

As a result, the above array’s final output should appear as follows:

const output = [['M', 'M', 'M', 'Z', 'M', 'B'], ['B', 'B', 'B', 'B', 'B', 'Z']];

It should be noted that elements from subarrays may alter their arrays if the sorting algorithm requires it.

Code:

const array = [['M', 'B', 'M', 'Z', 'B', 'B'], ['B', 'M', 'M', 'B', 'B', 'Z']];

const custom_sort = (array = []) => {
   const order = [].concat(...array.slice()),
   result = []; order.forEach((element, index) => {
      if (element === 'M') {
         const bIndex = order.indexOf('B');
         if (bIndex < index){
            order[bIndex] = 'M'; order[index] = 'B';
         };
      };
   })
   array.forEach(element => result.push(order.splice(0, element.length)))
   return result;
}
console.log(custom_sort(array));

The console will show the following output:

JavaScript Sort Multidimensional Array - Output 2

Here is another approach where you can sort multidimensional arrays by specifying a column.

Let us look into it by using an array as [[21, 'MM'], [76, 'AA'], [90, 'SS'],[03, 'GG']].

Code:

var array = [[21, 'MM'], [76, 'AA'], [90, 'SS'], [03, 'GG']];

array.sort(sort_function);

function sort_function(a, b) {
  if (a[0] === b[0]) {
    return 0;
  } else {
    return (a[0] < b[0]) ? -1 : 1;
  }
}
console.log(array);

The output of the above code is as follows:

JavaScript Sort Multidimensional Array - Output 3

Here, it was sorted by comparing the elements in the first column of the 2D array.

If necessary, the multidimensional array can be sorted by comparing the elements in the array’s second column, as in the below example.

Code:

var array = [[21, 'MM'], [76, 'AA'], [90, 'SS'], [03, 'GG']];

array.sort(sortFunction_col02);

function sortFunction_col02(a, b) {
  if (a[1] === b[1]) {
    return 0;
  } else {
    return (a[1] < b[1]) ? -1 : 1;
  }
}
console.log(array);

The expected output:

JavaScript Sort Multidimensional Array - Output 4

Conclusion

Sorting multidimensional arrays can easily sort and arrange the elements of an array by comparing them column-wise in ascending or descending order as per necessity. Be mindful that the sort() method uses the current array; hence, the array is altered.

The initial array is typically not affected by other array methods, which return a new array. This is crucial to remember if you utilize functional programming and anticipate that functions won’t have side effects.

Migel Hewage Nimesha avatar Migel Hewage Nimesha avatar

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.

Related Article - JavaScript Sort