korby - 1 month ago 21
Javascript Question

# Javascript Array.prototype.sort() unintentionally mutating array

I'm trying to sort an array of integers so as to put them in the order that will form the greatest integer. For example, [99, 901] should be sorted as [99, 901] because 99,901 > 90,199. And [91, 991] should be sorted as [991, 91] because 99,191 > 91,991.

To do this I am using Array.prototype.sort(), passing in the compare function in the code block below as the argument. The argument to this compare function is an array of arrays (each integer is first split into an array of single-digit integers): [[9,1],[9,9,1]].

My problem is that while this compare function works, it returns an array which has some elements truncated. Apparently this is due to the fact that I'm calling Array.prototype.shift() when it's necessary to compare the second (or third, fourth, etc.) elements of two integers. I didn't expect this but can't find a work-around.

For example, the code below outputs

``````[[9],[1,9]]
``````

whereas what I need is

``````[[9,9],[9,1,9]]
``````

Can you tell me how I can revise my compare function to get the output I am looking for?

Thanks!

``````var compare = function(a, b){

if(a.length === 1 || b.length === 1){
return (b[0] - a[0]);
}

else if(a[0] !== b[0]){
return compare(a[0], b[0]);
}

else if(a[0] === b[0]){
if(a.length !== 1){
a.shift();
}
if(b.length !== 1){
b.shift();
}
return compare(a, b);
}
};

var example = function(){

var digits = [[9,9],[9,1,9]];
digits.sort(compare);
console.log(digits);
};

example();
``````

``````var compare = function(a, b){