- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Constructing 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
- Related Articles
- Constructing an array of first n multiples of an input number in JavaScript
- Constructing array from string unique characters in JavaScript
- Constructing product array in JavaScript
- Constructing multiples array - JavaScript
- Finding the largest non-repeating number in an array in JavaScript
- Constructing an object from repetitive numeral string in JavaScript
- Constructing an array of addition/subtractions relative to first array element in JavaScript
- Constructing a string based on character matrix and number array in JavaScript
- Finding the largest and smallest number in an unsorted array of integers in JavaScript
- Picking the largest elements from multidimensional array in JavaScript
- Constructing an array of smaller elements than the corresponding elements based on input array in JavaScript
- Return the first duplicate number from an array in JavaScript
- Java program to find the largest number in an array
- How to find the largest number contained in a JavaScript array?
- Finding the nth missing number from an array JavaScript

Advertisements