- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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' ] ]
Advertisements