Split Integer into 2 digits and put into array Javascript - Stack Overflow

(Must read to understand exactly what I need)Iwould like to create a program that takes a number is

(Must read to understand exactly what I need) I would like to create a program that takes a number is input, such as: 12345 and then splits this number into 2 digit numbers and store it in a array. The array must look like this: [0]=45 [1]=23 [2]=1 . This means that the splitting of the numbers must start from the last digit of the number and not the first.

This is what I have until now:

var splitCount = []; // This is the array in which we store our split numbers
//Getting api results via jQuery's GET request
$.get(";id=UCJwchuXd_UWNxW-Z1Cg-liw&key=AIzaSyDUzfsMaYjn7dnGXy9ZEtQB_CuHyii4poc", function(result) {
    //result is our api answer and contains the recieved data
    //now we put the subscriber count into another variable (count); this is just for clarity
    count = result.items[0].statistics.subscriberCount;
    //While the subscriber count still has characters
    while (count.length) {
        splitCount.push(count.substr(0, 2)); //Push first two characters into the splitCount array from line 1
        count = count.substr(2); //Remove first two characters from the count string
    }       
    console.log(splitCount) //Output our splitCount array
});
<script src=".1.1/jquery.min.js"></script>

(Must read to understand exactly what I need) I would like to create a program that takes a number is input, such as: 12345 and then splits this number into 2 digit numbers and store it in a array. The array must look like this: [0]=45 [1]=23 [2]=1 . This means that the splitting of the numbers must start from the last digit of the number and not the first.

This is what I have until now:

var splitCount = []; // This is the array in which we store our split numbers
//Getting api results via jQuery's GET request
$.get("https://www.googleapis./youtube/v3/channels?part=statistics&id=UCJwchuXd_UWNxW-Z1Cg-liw&key=AIzaSyDUzfsMaYjn7dnGXy9ZEtQB_CuHyii4poc", function(result) {
    //result is our api answer and contains the recieved data
    //now we put the subscriber count into another variable (count); this is just for clarity
    count = result.items[0].statistics.subscriberCount;
    //While the subscriber count still has characters
    while (count.length) {
        splitCount.push(count.substr(0, 2)); //Push first two characters into the splitCount array from line 1
        count = count.substr(2); //Remove first two characters from the count string
    }       
    console.log(splitCount) //Output our splitCount array
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

but the problem with this is that if there are 5 digits for example: 12345 the the last digit will be in an array by itself like this: [0]=12 [1]=34 [2]=5 but I need the last array to have 2 digits and the first should be the one with one digit instead like this: [0]=1 [1]=23 [2]=45

Share edited Jan 18, 2017 at 12:36 Tomas Langkaas 4,7412 gold badges22 silver badges37 bronze badges asked Jan 17, 2017 at 18:39 KennethKenneth 493 silver badges9 bronze badges 4
  • Try starting from the end of the string – dex412 Commented Jan 17, 2017 at 18:43
  • But its an int? can you help me? – Kenneth Commented Jan 17, 2017 at 18:47
  • Make it a string by concatenating it to a "", then back to an int with paresInt() method – Seraf Commented Jan 17, 2017 at 20:37
  • You state that the output of 12345 should be like [0]=45 [1]=23 [2]=1 in the first part of your question, but like [0]=1 [1]=23 [2]=45, in the last part. Which is it? – Tomas Langkaas Commented Jan 18, 2017 at 11:48
Add a ment  | 

6 Answers 6

Reset to default 3

Split the string by using different regex for odd and even string lengths, Array#map it using Number, and Array#reverse the array:

function splitToNumbers(str) {
  return str.match(str.length  % 2 ? /^\d|\d{2}/g : /\d{2}/g).map(Number).reverse()
}
    
console.log(splitToNumbers('1234567'));

console.log(splitToNumbers('123456'));

Here is a snippet that fulfills the task. The function stores the values in the array myArray, and then outputs the array to a <p> element. The number is entered in the input box. Feel free to change this later.

function myFunction() {
  // Input field
  var input = document.getElementById('num');1
  // Length of the array storing the numbers
  var myArraySize = Math.floor(input.value.length / 2) + (input.value.length % 2);
  // The array storing the numbers
  var myArray = [];
  
  for (var i = 0; i < myArraySize; i++) {
    myArray[i] = input.value.slice(2*i,2*i+2);
  }
  // Output the array
  document.getElementById('demo').innerHTML = myArray;
}
<input id="num" type="text" onkeyup="myFunction()" />
<p id="demo">Result</p>

You could split the string with a regular expression and reverse the array.

This answer is heavily inspired by this answer.

var regex = /(?=(?:..)*$)/;

console.log('12345'.split(regex).reverse());
console.log('012345'.split(regex).reverse());
.as-console-wrapper { max-height: 100% !important; top: 0; }

No need for regex or expensive calculations. You might simply do as follows;

var n = 250847534,
steps = ~~Math.log10(n)/2,
  res = [];
for(var i = 0; i <= steps; i++) {
  res.push(Math.round(((n /= 100)%1)*100));
  n = Math.trunc(n);
}
console.log(res);

Amending your code a little

var splitCount = []; // This is the array in which we store our split numbers
//Getting api results via jQuery's GET request
$.get("https://www.googleapis./youtube/v3/channels?part=statistics&id=UCJwchuXd_UWNxW-Z1Cg-liw&key=AIzaSyDUzfsMaYjn7dnGXy9ZEtQB_CuHyii4poc", function(result) {
    //result is our api answer and contains the recieved data
    //now we put the subscriber count into another variable (count); this is just for clarity
    count = result.items[0].statistics.subscriberCount;
    //While the subscriber count still has characters
    while (count.length) {
        splitCount.push(count.substr(-2)); //Push last two characters into the splitCount array from line 1
        if(count.length > 1) {
           count =  count.substr(0, count.length - 2); //Remove first last two characters from the count string
        } else {
           break;
        }
    }       
    console.log(splitCount) //Output our splitCount array
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

There are several ways to approach your problem, from nice one-liners using regexes (like Ori Dori or Nina Scholz) to Redu's answer that works directly on numbers, avoiding strings.

Following the logic of your code example and ments, here is an alternative that converts the number to a string, loops over it backwards to extract two digits at a time, converts these back to a number (with the unary plus operator), and outputs this number to a result array:

function extract(num) {
  var s = '0' + num, //convert num to string
    res = [],
      i;
  for(i = s.length; i > 1; i -= 2) {
    //loop from back, extract 2 digits at a time, 
    //output as number,
    res.push(+s.slice(i - 2, i));
  }
  return res;
}

//check that 12345 outputs [45, 23, 1]
console.log(extract(12345));

//check that 123456 outputs [56, 34, 12]
console.log(extract(123456));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744918574a4600988.html

相关推荐

  • Split Integer into 2 digits and put into array Javascript - Stack Overflow

    (Must read to understand exactly what I need)Iwould like to create a program that takes a number is

    1天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信