Constructing largest number from an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in an array of numbers as the first and the only argument.

The function should string together the numbers present in the array such that form the greatest possible number that can be formed from those given set of numbers.

For example −

If the input array is −

const arr = [5, 45, 34, 9, 3];

Then the output should be −

const output = '9545343';

Example

Following is the code −

const arr = [5, 45, 34, 9, 3];
const largestNumber = (arr = []) => {
   if(arr.every( n => n === 0)){
      return '0';
   }
   arr.sort((a, b) => {
      const s1 = new String(a);
      const s2 = new String(b);
      const first = s1 + s2;
      const second = s2 + s1;
      if(first > second){
         return -1;
      }else if(first < second){
         return 1;
      };
      return 0;
   });
   return arr.join('');
};
console.log(largestNumber(arr));

Output

Following is the console output −

9545343
raja
Published on 18-Jan-2021 04:54:51
Advertisements