Bishal Jain
Bishal Jain

Reputation: 209

how to form the largest number from a set of an array in javaScript

I have an array with arr = [1,3,34,44,4,45,6,76,9,98,23] and want the largest number to be formed from the array above. O/P number is 99876645444343231.

I tried doing it in for these set of number and that is working fine for 2 digits but not for more then that. Can anyone suggest a generic answer?

Upvotes: 2

Views: 3836

Answers (4)

Vic
Vic

Reputation: 33

How about:

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

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

Explanation:

The ... syntax allows an iterable such as an array expression or string to be spread in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

The concatenation of '' at the beginning of the sorting pass will implicitly cast the contextual a and b to string and would have the following mechanism each sorting pass:

n = 0

Let a = '1', b = '9'

What is (b + a) - (a + b) e.g. '91' - '19' ?

negative: sort a to an index lower than b, i.e. a comes first.

positive: sort b to an index lower than a, i.e. b comes first.

zero: leave a and b unchanged with respect to each other.

... N

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

Upvotes: 2

Abhijit
Abhijit

Reputation: 252

Write a comparison function compare() and use it to sort numbers. Given two numbers first and second, we compare two numbers firstsecond (second appended at the end of first) and secondfirst (first appended at the end of second). If firstsecond is larger, then first should come before second in output, else second should come before first.

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

function getLargestNumber(arr){
    var largestNumber = arr.join('')
    return largestNumber
}
var arr = [1,3,34,44,4,45,6,76,9,98,23]
sortArray(arr)
var result = getLargestNumber(arr)
alert(result)

Upvotes: 3

Vishal-L
Vishal-L

Reputation: 1347

  1. Sort the array in descending order of first digit of each number(by converting to array of strings).
  2. Join all numbers of sorted array.

function swapArrayElements(arr, indexA, indexB) {
  let temp = arr[indexA];
  arr[indexA] = arr[indexB];
  arr[indexB] = temp;
}

function largestNumber(arr) {
	let arrOfStrings;

	arrOfStrings = arr.map(n => n.toString());

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

	return arrOfStrings.join('');
}

let arr = [1,3,34,44,4,45,6,76,9,98,23];
const largestNum = largestNumber(arr);

console.log(largestNum);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

You could take an array with stringed values and the concatinated values of a and b and the value of b and a and take the delta of it for sorting, which reflects the sort order of the two string for a greater value for later joining.

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]));

Comparison with a simple descending sorting by string, which returns the wrong result (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(''));

Upvotes: 6

Related Questions