How to sort the digits within subgroups of a number's digits which are separated by "0", and remove the zeros?
function dividerSort(num){
var result = '';
var items = num.toString().split('0'); // items = ["741", "852", "159"]
items.forEach( item => {
result = result + item.split('').sort().join('') // see Explanation
});
console.log('Result: ', result);
}
dividerSort(74108520159); // Result: 147258159
Explanation: forEach() item
in items
split at every charachter item.split('')
.
Example: "741"
becomes an array ['7', '4', '1']
. This array can be sorted simply with Array.sort() so it becomes ['1', '4', '7']
which will then be joined back together to a string with Array.join() . At every iteration concatenate the result to result...
You could split the string with zero, map splitted substrings with splitted by chcaracter, sort them and join them. Then join the mapped part strings.
function dividerSort(num){
return +String(num)
.split('0')
.map(s => s.split('').sort().join(''))
.join('');
}
console.log(dividerSort(74108520159)); // 147258159
you can use String.split()
method to split.
usage
let number = 1230456098;
let stringified = number.toString(); // to use String.split ()
let splitted = stringified.split("0"); // ["123", "456", "98"]
// convert those "string" elements of `splitted` array into numbers, and then apply sorting algorithm.
splitted = splitted.map(split=>parseInt(split)); // [123, 456, 98]
TLDR;
- convert that integer to a string, using
Number.toString()
, - use String.split() to split the string,
- map through the splitted array and convert those string elements into numbers, using
splitted.map(split=>parseInt(split));