Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort the digits within subgroups of a number's digits which are separated by "0", and remove the zeros?

Tags:

javascript

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);
like image 533
Yohanes Avatar asked Nov 21 '20 08:11

Yohanes


3 Answers

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...

like image 154
caramba Avatar answered Oct 23 '22 12:10

caramba


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
like image 2
Nina Scholz Avatar answered Oct 23 '22 10:10

Nina Scholz


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;

  1. convert that integer to a string, using Number.toString(),
  2. use String.split() to split the string,
  3. map through the splitted array and convert those string elements into numbers, using splitted.map(split=>parseInt(split));
like image 2
Rahul Dahal Avatar answered Oct 23 '22 11:10

Rahul Dahal