I have a variable that contains an integer number with the condition that the number 0 (zero) in the variable is a separator between one number and another. The numbers will be separated and sorted based on the numbers in the numbers themselves. After that, the ordered numbers will be combined again without a separator with the output in the form of an integer number.
So example:
dividerSort(74108520159);
the output I want is
147258159
but my output is:
112455789
This is so far I try, hope you can help me figure out
function dividerSort(num){
const divider = 0
let getNum = Array.from(String(num), Number)
getNum = getNum.filter(item =>{
return item !== divider
})
getNum = getNum.sort()
getNum = getNum.join('');
console.log(getNum);
}
dividerSort(74108520159);
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.
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]
Number.toString()
,splitted.map(split=>parseInt(split));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With