Sorting 2-D array of strings and finding the diagonal element using JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Updated on 21-Apr-2021 06:44:33

Advertisements