如何在javaScript中从一组数组中形成最大数字

时间:2022-08-03 20:24:45

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.

我有一个arr = [1,3,34,44,4,45,6,76,9,98,23]的数组,并希望从上面的数组中形成最大的数字。 O / P号码是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?

我尝试使用这些数字组合,这对于2位数字工作正常,但不是更多。任何人都可以提出通用答案吗?

4 个解决方案

#1


1  

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.

写一个比较函数compare()并用它来排序数字。给定两个数字第一和第二,我们比较两个数字firstsecond(第二个附加在第一个结尾)和secondfirst(第一个附加在第二个结尾)。如果firstsecond较大,那么首先应该在输出中的第二个之前,否则第二个应该在第一个之前。

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)

#2


2  

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.

您可以使用带有stringed值的数组以及a和b的连续值以及b和a的值,并将其取值用于排序,这反映了两个字符串的排序顺序,以便以后加入更大的值。

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(''));

#3


0  

  1. Sort the array in descending order of first digit of each number(by converting to array of strings).
  2. 按每个数字的第一个数字的降序对数组进行排序(通过转换为字符串数组)。

  3. Join all numbers of sorted array.
  4. 加入所有排序数组。

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

#4


0  

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:

''在排序过程开始时的串联将隐式地将上下文a和b强制转换为字符串,并且每个排序传递将具有以下机制:

n = 0

n = 0

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

设a ='1',b ='9'

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

什么是(b + a) - (a + b),例如'91' - '19'?

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

否定:将a排序为低于b的索引,即a首先出现。

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

正:将b排序为低于a的索引,即b首先出现。

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

零:相互保持a和b不变。

... 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

#1


1  

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.

写一个比较函数compare()并用它来排序数字。给定两个数字第一和第二,我们比较两个数字firstsecond(第二个附加在第一个结尾)和secondfirst(第一个附加在第二个结尾)。如果firstsecond较大,那么首先应该在输出中的第二个之前,否则第二个应该在第一个之前。

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)

#2


2  

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.

您可以使用带有stringed值的数组以及a和b的连续值以及b和a的值,并将其取值用于排序,这反映了两个字符串的排序顺序,以便以后加入更大的值。

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(''));

#3


0  

  1. Sort the array in descending order of first digit of each number(by converting to array of strings).
  2. 按每个数字的第一个数字的降序对数组进行排序(通过转换为字符串数组)。

  3. Join all numbers of sorted array.
  4. 加入所有排序数组。

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

#4


0  

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:

''在排序过程开始时的串联将隐式地将上下文a和b强制转换为字符串,并且每个排序传递将具有以下机制:

n = 0

n = 0

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

设a ='1',b ='9'

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

什么是(b + a) - (a + b),例如'91' - '19'?

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

否定:将a排序为低于b的索引,即a首先出现。

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

正:将b排序为低于a的索引,即b首先出现。

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

零:相互保持a和b不变。

... 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