Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sorting 2-D array of strings and finding the diagonal element using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of n strings. Each string in the array consists of exactly n characters.
Our function should first sort the array in alphabetical order, then return the string formed by the characters present at the principal diagonal starting from the top left corner.
Understanding the Process
The solution involves two main steps:
- Sort the array of strings alphabetically
- Extract diagonal characters where row index equals column index (i === j)
Example
Let's work through a complete example:
const arr = [
'star',
'abcd',
'calm',
'need'
];
const sortPickDiagonal = (array) => {
// Create a copy and sort alphabetically
const copy = array.slice();
copy.sort();
console.log("Original array:", array);
console.log("Sorted array:", copy);
let res = '';
for(let i = 0; i < copy.length; i++){
for(let j = 0; j < copy[i].length; j++){
if(i === j){
res = res + copy[i][j];
console.log(`Diagonal element at [${i}][${j}]: ${copy[i][j]}`);
}
}
}
return res;
};
console.log("Final result:", sortPickDiagonal(arr));
Original array: [ 'star', 'abcd', 'calm', 'need' ] Sorted array: [ 'abcd', 'calm', 'need', 'star' ] Diagonal element at [0][0]: a Diagonal element at [1][1]: a Diagonal element at [2][2]: e Diagonal element at [3][3]: r Final result: aaer
How It Works
After sorting, our array becomes: ['abcd', 'calm', 'need', 'star']
The diagonal extraction works as follows:
- Position [0][0]: 'a' from "abcd"
- Position [1][1]: 'a' from "calm"
- Position [2][2]: 'e' from "need"
- Position [3][3]: 'r' from "star"
Optimized Solution
Here's a more concise version using array methods:
const sortPickDiagonalOptimized = (array) => {
return array
.slice()
.sort()
.map((str, index) => str[index])
.join('');
};
const testArray = ['star', 'abcd', 'calm', 'need'];
console.log("Optimized result:", sortPickDiagonalOptimized(testArray));
Optimized result: aaer
Key Points
- Always create a copy of the original array before sorting to avoid mutation
- The diagonal elements are at positions where row index equals column index
- JavaScript's
sort()method performs lexicographic (alphabetical) sorting by default - The input must be a square matrix (n×n) for this solution to work correctly
Conclusion
This solution demonstrates sorting arrays and matrix diagonal extraction. The key insight is identifying diagonal positions where i === j after alphabetical sorting.
