1

(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.com/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.com/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

4
  • Try starting from the end of the string Commented Jan 17, 2017 at 18:43
  • But its an int? can you help me? Commented Jan 17, 2017 at 18:47
  • Make it a string by concatenating it to a "", then back to an int with paresInt() method 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? Commented Jan 18, 2017 at 11:48

6 Answers 6

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'));

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

1

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; }

Comments

1

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);

Comments

0

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.com/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.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments

0

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 comments, 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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.