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