
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
Construct Largest Number from an Array in JavaScript
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
Advertisements