简体   繁体   中英

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 a_list is ['45', '30', '50', '1'] the smallest possible string will be '1304550' which is right, but what if a_list is ['32', '3'] given this current code I will get '332' which is not correct because '323' is the smallest possible string. Hope that helps.

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.

 function sort(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' .

 function sort(a, b) { return (a + b) - (b + a) || a - b; } console.log([['45', '30', '50', '1'], ['32', '3']].map(a => a.sort(sort).join(''))); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM