Dragan Milosevic
Dragan Milosevic

Reputation: 69

How to combine array of numbers so resulting number is as large as possible in javaScript

I have an array of positive integers as an input in javascript. Output should be the greatest possible integer created out of combined array elements in input. Examples:

  1. input: [80,35,2,9,45,8] output: 988045352
  2. input: [509,7,49,21,527,2,742] output: 774252750949221

I think I know the logic that could be used but fails to pull it off...

I guess that two array elements next to each other should be concatenated in both directions and this values to be compared, which one is the bigger and then use this logic to sort all array elements. However, I can't do it in javaScript.

Thank you.

Upvotes: 2

Views: 584

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386654

You could check if the string is smaller than the switched value.

function sort(a, b) {
    return ('' + b + a) - ('' + a + b);
}

console.log(+[509, 7, 49, 21, 527, 2, 742].sort(sort).join(''));
console.log(+[80, 35, 2, 9, 45, 8].sort(sort).join(''));

Upvotes: 1

MaxZoom
MaxZoom

Reputation: 7753

After converting integers to Strings, compare their unions:

function Comparator(a, b) {
  var s1 = a.toString();
  var s2 = b.toString();
  return (s2+s1).localeCompare(s1+s2);
}

var myArray = [509, 7, 49, 21, 527, 2, 742].sort(Comparator);
console.log(myArray.join(''));

Upvotes: 0

R. Schifini
R. Schifini

Reputation: 9313

Do this:

a = [80,35,2,9,45,8];

result = a.sort((x,y)=> ""+x+y < ""+y+x);

result:

[ 9, 8, 80, 45, 35, 2 ]

And for the second one the result is:

[ 7, 742, 527, 509, 49, 2, 21 ]

If you want a single number use .join("") after the sort.

Upvotes: 6

Related Questions