How to use Array In Javascript

The array is used to select the largest number from the data here. We are creating array names as “temp” that consist of 10 elements initialized to zero, where each of the elements corresponds to the digit [0-9]. Then we are iterating over the input numbers array and incrementing the count of each digit correlation in the “temp” array. There is an empty string, “largestNumber,” that stores the final result. We iterate in the reverse order, from 9 down to 0. For each digit [i], we are checking the count raised in [i]. Then it appends the digit ‘i’ to the largest number, t[i] times, to construct the largest number.

Syntax:

let temp = Array(10).fill(0);

Example: In this example, we will construct the largest number from the digits using the Array.

Javascript




let inputNumbers = [8, 3, 4, 7, 9];
let length = inputNumbers.length;
let temp = Array(10).fill(0);
  
for (let i = 0; i < length; i++) {
  temp[inputNumbers[i]]++; 
}
let largestNumber = '';
for (let i = 9; i >= 0; i--) {
  while (temp[i]-- > 0) { 
    largestNumber += String(i); 
  }
}
console.log(largestNumber);


Output

98743


JavaScript Program to Construct Largest Number from Digits

In this article, we have given a set of digits, and our task is to construct the largest number generated through the combination of these digits. Below is an example for a better understanding of the problem statement.

Example:

Input: arr[] = {4, 9, 2, 5, 0}
Output: Largest Number: 95420

Table of Content

  • Using sort() Method
  • Using Math.max Method
  • Using Loops
  • Using Array

Similar Reads

Using sort() Method

The sort function is used to sort the input digits either in ascending or descending order. As we need to construct the largest number, we will sort the input data in the descending order and then concatenate the sorted digits to construct the largest number....

Using Math.max Method

...

Using Loops

The Math.max method is used to find the largest number from the given numbers. We are randomly finding the maximum digit from the input set of numbers and storing the result in a new variable. We are using the Math.max method to find the maximum digit from the set of numbers....

Using Array

...

Contact Us