Sort in multi-dimensional arrays in JavaScript



Suppose, we have the following array of arrays −

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

We are required to write a JavaScript function that takes in one such array.

The function should sort all the subarrays of the given array internally according to these rules −

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

Therefore, the final output for the above array should look like −

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

Note that elements from subarrays can change their arrays if the sorting algorithm makes them to do so.

Example

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

Output

And the output in the console will be −

[ [ 'A', 'A', 'A', 'H', 'A', 'F' ], [ 'F', 'F', 'F', 'F', 'F', 'H' ] ]
Updated on: 2020-11-21T06:03:57+05:30

754 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements