Sort in multi-dimensional arrays in JavaScript

Sorting multi-dimensional arrays in JavaScript requires handling each subarray while maintaining specific sorting rules. This article demonstrates how to sort elements within subarrays based on custom conditions.

Problem Statement

Suppose we have the following array of arrays:

const arr = [
  ["A","F","A","H","F","F"],
  ["F","A","A","F","F","H"]
];

We need to write a JavaScript function that sorts all subarrays according to these rules:

  • If the elements are not either "A" or "F", they should maintain their position
  • If the element is either "A" or "F", they should be sorted alphabetically

Elements from subarrays can change their arrays if the sorting algorithm requires it.

Expected Output

const output = [
  ["A","A","A","H","A","F"],
  ["F","F","F","F","F","H"]
];

Solution Implementation

const arr = [
  ["A","F","A","H","F","F"],
  ["F","A","A","F","F","H"]
];

const customSort = (arr = []) => {
  const order = [].concat(...arr.slice());
  const res = [];
  
  order.forEach((el, ind) => {
    if (el === 'A') {
      const fIndex = order.indexOf('F');
      if (fIndex  res.push(order.splice(0, el.length)));
  return res;
}

console.log(customSort(arr));
[ [ 'A', 'A', 'A', 'H', 'A', 'F' ], [ 'F', 'F', 'F', 'F', 'F', 'H' ] ]

How It Works

The algorithm works in three main steps:

  1. Flatten the array: All subarrays are concatenated into a single array using concat(...arr.slice())
  2. Sort A and F elements: The function iterates through elements, swapping 'A' elements with earlier 'F' elements to maintain alphabetical order
  3. Reconstruct subarrays: Elements are redistributed back into subarrays of their original lengths using splice()

Alternative Approach

Here's a more straightforward approach using array sorting methods:

const arr = [
  ["A","F","A","H","F","F"],
  ["F","A","A","F","F","H"]
];

const alternativeSort = (arr = []) => {
  // Extract all A and F elements
  const sortableElements = [];
  const positions = [];
  
  arr.forEach((subArr, i) => {
    subArr.forEach((el, j) => {
      if (el === 'A' || el === 'F') {
        sortableElements.push(el);
        positions.push([i, j]);
      }
    });
  });
  
  // Sort A and F elements
  sortableElements.sort();
  
  // Create result array
  const result = arr.map(subArr => [...subArr]);
  
  // Place sorted elements back
  positions.forEach((pos, index) => {
    result[pos[0]][pos[1]] = sortableElements[index];
  });
  
  return result;
};

console.log(alternativeSort(arr));
[ [ 'A', 'A', 'A', 'H', 'A', 'F' ], [ 'F', 'F', 'F', 'F', 'F', 'H' ] ]

Key Points

  • Multi-dimensional array sorting requires flattening and reconstructing arrays
  • Custom sorting rules can be implemented using conditional logic
  • Elements can move between subarrays during the sorting process
  • Non-target elements maintain their original positions

Conclusion

Sorting multi-dimensional arrays with custom rules involves flattening the structure, applying sorting logic, and reconstructing the original dimensions. The key is maintaining the relative positions of non-target elements while sorting the specified ones.

Updated on: 2026-03-15T23:19:00+05:30

803 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements