Return The Smallest Possible Join From Array Javascript
I have this code which works good for this array: ['45', '30', '50', '1']. function penalty(a_list) { return a_list.sort((a, b) => a - b).join(''); } for example: given that
Solution 1:
You could take 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 smaller value for later joining.
If integers are supplied, then the values need to be converted to string in the sort callback.
functionsort(a, b) {
return (a + b) - (b + a);
}
console.log([['45', '30', '50', '1'], ['32', '3']].map(a => a.sort(sort).join('')));
For a stable sort, you could move smaller values to top (which does not affect the later joined string). This sorts '3'
before '33'
.
functionsort(a, b) {
return (a + b) - (b + a) || a - b;
}
console.log([['45', '30', '50', '1'], ['32', '3']].map(a => a.sort(sort).join('')));
Post a Comment for "Return The Smallest Possible Join From Array Javascript"