- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' ] ]
- Related Articles
- Multi Dimensional Arrays in Javascript
- Flattening multi-dimensional arrays in JavaScript
- Dump Multi-Dimensional arrays in Java
- How to initialize multi-dimensional arrays in C#?
- How to define multi-dimensional arrays in C#?
- Does Java support multi-dimensional Arrays?
- Multi-Dimensional Array in Javascript
- How do we use multi-dimensional arrays in C#?
- How to define multi-dimensional arrays in C/C++?
- Get the Inner product of two multi-dimensional arrays in Python
- Converting multi-dimensional array to string in JavaScript
- Greatest element in a Multi-Dimensional Array in JavaScript
- How to Map multi-dimensional arrays to a single array in java?
- C++ Program to Add Two Matrix Using Multi-dimensional Arrays
- C++ Program to Multiply Two Matrix Using Multi-dimensional Arrays

Advertisements