Creating the greatest possible number using elements from an array in JavaScript

Given the array

arr = [1,3,34,44,4,45,6,76,9,98,23]
, my goal is to create the largest possible number from those values. The output should be 99876645444343231.

I attempted this with a solution that works well for two-digit numbers, but struggles with larger numbers. Does anyone have a more generic approach to solving this problem?

Answer №1

You can organize an array containing strings along with the concatenated values of a and b, as well as the value of b followed by a. By calculating the delta between them for sorting, you can determine the order in which the two strings should be arranged to yield a higher combined value when joined later.

function getLargest(array) {
    return array
        .map(String)
        .sort((a, b) => (b + a) - (a + b))
        .join('');
}

console.log(getLargest([1, 3, 34, 44, 4, 45, 6, 76, 9, 98, 23]));

A comparison is also made with a simple descending sorting method using strings, but it produces incorrect results (as shown in the second line).

function getLargest(array) {
    return array
        .map(String)
        .sort((a, b) => (b + a) - (a + b))
        .join('');
}

console.log(getLargest([1, 3, 34, 44, 4, 45, 6, 76, 9, 98, 23]));
console.log([1, 3, 34, 44, 4, 45, 6, 76, 9, 98, 23].sort().reverse().join(''));

Answer №2

Create a custom comparison function named compare() to organize numbers in ascending order. Compare two numbers, first and second, by concatenating them in different orders (firstsecond and secondfirst). Determine the correct positioning based on which concatenated number is larger.

function sortNumberArray(array){
    array.sort(function compare(first,second) {
        var firstsecond ='' + first + second;
        var secondfirst ='' + second + first;
        return firstsecond>secondfirst ? -1:1;
    })
}

function findLargestNum(array){
    var largestNum = array.join('')
    return largestNum
}
var numArray = [1,3,34,44,4,45,6,76,9,98,23]
sortNumberArray(numArray)
var finalResult = findLargestNum(numArray)
alert(finalResult)

Answer №3

Why not try this:

const concatenateNumbers = (...nums) => nums.sort((a, b) => ('' + b + a) - ('' + a + b)).join('');

console.log(concatenateNumbers(1, 3, 34, 44, 4, 45, 6, 76, 9, 98, 23)); //99876645444343231
console.log(concatenateNumbers(2, 20, 24, 6, 8)); //8624220

Explanation:

The ... syntax allows for spreading iterable elements in places where arguments or array elements are expected. By concatenating an empty string ('') during the sorting process, we implicitly convert values to strings before comparison.

References:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Answer №4

  1. Arrange the elements in the array based on the first digit of each number in descending order (after converting them into strings).
  2. Concatenate all numbers after sorting.

function switchArrayElements(inputArr, indexA, indexB) {
  let temp = inputArr[indexA];
  inputArr[indexA] = inputArr[indexB];
  inputArr[indexB] = temp;
}

function findLargestNumber(inputArr) {
let stringArr;

stringArr = inputArr.map(num => num.toString());

for(let i = 0; i < stringArr.length - 1; i++) {
for(let j = i + 1; j < stringArr.length; j++) {
if(parseInt(stringArr[i] + stringArr[j]) < parseInt(stringArr[j] + stringArr[i])) {
switchArrayElements(stringArr, i, j);
}
}
}

return stringArr.join('');
}

let inputArr = [1,3,34,44,4,45,6,76,9,98,23];
const result = findLargestNumber(inputArr);

console.log(result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying Mathematical Addition Using Two Arrays in Python

How can I create a code to visually represent the addition operation between two arrays (row-wise)? I'm not interested in the result, but rather want to demonstrate the process. Below is my attempt so far, but it's not yielding the correct output ...

I'm experiencing some strange symbols on my page that look like ''. It appears to be a problem occurring between the servlet and the Javascript. How can I resolve this issue?

After retrieving a CSV file from my servlet, I noticed that characters like 'é', 'á' or 'õ' are not displaying properly on my page. Strangely, when I access the servlet directly via browser, everything appears fine. I atte ...

What does the main attribute in npm stand for?

The command npm init generates a file called package.json. The contents typically look like this: { "name": "webpack-tut", "version": "1.0.0", "description": "", "main": "index.js", .... } I came across this information in the official documen ...

Sending an array as a post variable: A step-by-step guide

Currently, I am working with Perl and a Perl framework (unsure if this detail is crucial). My goal is to generate a variable number of input fields within a form, allowing users to select multiple items from a list. Subsequently, these selections would b ...

What is the best way to invoke a JavaScript function after an event or from a user interface?

I am struggling to call a JavaScript subroutine on the client-side after the server has completed its task. Even though I have tried putting breakpoints in <% ... %> areas between <script...> and </script>, it seems that VS2010 does not a ...

Ways to conceal an element when it appears in the initial section of a page

I currently have a single-page website consisting of 4 sections which are not scrollable. To navigate between these sections, I have implemented a burger menu button with a fixed position to ensure it remains visible on all sections except the first one. ...

An error has occurred in the tipo-struttura component file in an Angular application connected with a Spring backend and SQL database. The error message indicates that there is a TypeError where the

Working on my project that combines Spring, Angular, and MYSQL, I encountered a challenge of managing three interconnected lists. The third list depends on the second one, which in turn relies on user choices made from the first list. While attempting to l ...

Retrieving data from the firebase database by filtering based on the child's specific value

Looking at the firebase database, I can see that only the 'name' field is available. Now, I am trying to retrieve the 'quantity' value associated with that specific 'name'. Can someone provide me with a sample firebase query i ...

Focus is lost on React input after typing the initial character

Whenever I input text, the focus is lost. All my other components are working fine except this one. Any ideas why this might be happening? I attempted to create separate components and render them in my switch statement, but it still doesn't work. O ...

JavaScript error message stating that the setAttribute function is null

As a newcomer to JS, I am currently working on creating a task list webpage that allows users to submit projects and create task lists within each project with designated due dates. In order to generate unique ID tags for projects and tasks, I utilized UU ...

Assigning values to elements in an array without having prior knowledge of their

Similar Question: Finding index of matched array key In the code snippet, I'm using $params[ltrim($part, ':')] = null; to create an array that appears as follows: Array ( [id] => [random] => [something] => ) I ...

Issues arise when attempting to pass multiple parameters to the getJSON function

Being new to Ajax-Json script, I am currently exploring a shopping cart example. However, the feature to remove items from the cart is not functioning as expected. Below is the function in my code: js //Remove items from cart $("#shopping-cart-result ...

Incorporating JavaScript unit tests into an established website

I am facing a challenge with testing my JavaScript functions in the context of a specific webpage. These functions are tightly integrated with the UI elements on the page, so I need to be able to unit-test the entire webpage and not just the functions them ...

encountering plupload issue during file upload

While utilizing the Plupload solution to upload multiple files simultaneously, an error message appears in the browser console: NS_ERROR_DOM_BAD_URI: Access to restricted URI denied The code halts at this point: new n.DOMException(n.DOMException.INVALID_S ...

Use YUI to parse JSON data enclosed in square brackets and curly braces within a packet

Recently, I have been diving into the world of JSON, JavaScript, and YUI while working on a homework assignment. The JSON packet I am dealing with has the following structure: [{"id":"1234", "name":"some description","description":"url":"www.sd.com"}, {sa ...

Coming up with a dynamic array that is populated with random numbers can be a challenging task

*I encounter an issue when attempting to populate an Array with random numbers. I suspect the problem lies within the pointers. The error message shows ' ptr[i][j]= rand() % 40000 +5; '* Error Name: subscripted value is neither array nor pointer ...

Static addition of the Button to the parent div is crucial for seamless

Introduction: My current project involves managing interns, and I am focusing on the employee side. Employees have the ability to add, edit, and delete interns through modal popups. Strategy: To avoid unnecessary repetition of code, I decided to create a ...

There seems to be an issue with the hidden field value not being properly set within the

I created a function called getConvertionValue. Inside this function, I make an ajax call to the getCurrencyConvertion function in the controller. function getConvertionValue(from, to) { if (from != to) { $.ajax({ url: base_url + 'admin/o ...

What is the best way for an object to recognize if its value matches a key in another object, and then retrieve that value

Is there a way to make an object detect if its value is equal to another object's key and then retrieve it? Let's consider the following object named: AnswerString let AnswerString ={ 0: "B", 1: "x" } and the answers are in different objects, ...

Stop users from repeating an action

We are encountering challenges with users repeating a specific action, even though we have measures in place to prevent it. Here is an overview of our current approach: Client side: The button becomes disabled after one click. Server side: We use a key h ...