
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 2D Array of Strings and Find Diagonal Element Using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of n strings. And each string in the array consists of exactly n characters.
Our function should first sort the array in alphabetical order. And then return the string formed by the characters present at the principal diagonal starting from the top left corner.
Example
Following is the code −
const arr = [ 'star', 'abcd', 'calm', 'need' ]; const sortPickDiagonal = () => { const copy = arr.slice(); copy.sort(); 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]; }; }; }; return res; }; console.log(sortPickDiagonal(arr));
Output
aaer
Advertisements