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 −

 Live Demo

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
Updated on: 2021-04-21T06:44:33+05:30

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements