separating numbers into sum of positional digits in javascript - javascript

I'm working with freecodecamp studies and need to find a way to turn a number into sum of positional digits like [1234] to [1000,200,30,4].
Code looks like this:
for(var i=0;i<newArr.length;i++){
var order = newArr.length-1 - i;
newArr.splice(i,1,newArr[i]*1e(order));
}
Here newArr will be 1234.
Node gives error: invalid token 1e(order).
Need some advice how to make it right.

I think you can use the below logic
var n = 123456;
n=n.toString();
var arr = n.split("");
var b = arr.map(function(x,i) {
return x * Math.pow(10, (arr.length-i-1));;
});
console.log(b);

var a = 1234
b = []
while(a>0){
b.unshift(a%10 * (10 ** b.length))
a = parseInt(a/10)
}
console.log(b)

Number.prototype.padRight = function (n,str) {
return (this < 0 ? '-' : '') + (Math.abs(this)+ Array(n-String(Math.abs(this)).length+1).join(str||'0'));
}
var digits = "1234"
var tempCounter= digits.length;
var result=[];
for(var i=0;i<digits.length;i++,tempCounter--){
result.push(parseInt(digits[i]).padRight(tempCounter))
}
console.log(result);

Related

Return multiple strings from function based on variable number

I have a string
var str = 'string'
I have a multiplier
var mult = 3
I want to return stringstringstring
The mult will change. Basically mult is kind of like a power but this is a string not a number. And I need to return multiple strings. I'm thinking of looping where mult = the number of times to loop and each would conceptually 'push' but I don't want an array or something like =+ but not a number. I'm thinking I could have the output push to an array the number of times = to mult, and then join the array - but I don't know if join is possible without a delimiter. I'm new at javascript and the below doesn't work but it's what I'm thinking. There's also no ability to input a function in the place I'm running javascript and also no libraries.
var loop = {
var str = 'string'
var arr = [];
var mult = 3;
var i = 0
for (i = 0, mult-1, i++) {
arr.push('string'[i]);
}
}
var finalString = arr.join(''); // I don't know how to get it out of an object first before joining
Not sure if what I want is ridiculous or if it's at all possible
You mean something like below,
var str = 'string'
var mult = 3
var str2 = ''
for(i = 0; i < mult; i++) {
str2 += str
}
console.log(str2)
var str = 'string'
var mult = 3;
var sol =""
while(mult--) {
sol +=str;
}
console.log(sol)
Using resusable function:
const concatStr= (str, mult)=>{
var sol =""
while(mult--) {
sol +=str;
}
console.log(sol)
}
concatStr("string",3)
Using the inbuilt Array.from method:
var str = "string"
var mult = 3
var sol = Array.from({length: mult}, ()=> str).join("")
console.log(sol)
function concatString(str, mult) {
var result = ''
for(i = 0; i < mult; i++) {
result = result.concat(str);
}
return result;
}
const value = concatString('string', 3);
console.log(value);
Also you can use array inbuilt methods,
const mult = 3, displayVal = 'str';
Array(mult).fill(displayVal).join('');
// the string object has a repeat method
console.log('string'.repeat(3));

How do I match the numbers sequence rising?

I have a string contains just numbers. Something like this:
var numb = "5136789431235";
And I'm trying to match ascending numbers which are two or more digits. In string above I want this output:
var numb = "5136789431235";
// ^^^^ ^^^
Actually I can match a number which has two or more digits: /[0-9]{2,}/g, But I don't know how can I detect being ascending?
To match consecutive numbers like 123:
(?:(?=01|12|23|34|45|56|67|78|89)\d)+\d
RegEx Demo
To match nonconsecutive numbers like 137:
(?:(?=0[1-9]|1[2-9]|2[3-9]|3[4-9]|4[5-9]|5[6-9]|6[7-9]|7[8-9]|89)\d)+\d
RegEx Demo
Here is an example:
var numb = "5136789431235";
/* The output of consecutive version: 6789,123
The output of nonconsecutive version: 136789,1234
*/
You could do this by simply testing for
01|12|23|34|45|56|67|78|89
Regards
You just need to loop through each number and check next one. Then add that pair of values to a result variable:
var numb = "5136789431235";
var res = [];
for (var i = 0, len = numb.length; i < len-1; i++) {
if (numb[i] < numb[i+1]) res.push(new Array(numb[i],numb[i+1]))
}
res.forEach(function(k){console.log(k)});
Here is fiddle
Try this to match consecutive numbers
var matches = [""]; numb.split("").forEach(function(val){
var lastNum = 0;
if ( matches[matches.length-1].length > 0 )
{
lastNum = parseInt(matches[matches.length-1].slice(-1),10);
}
var currentNum = parseInt(val,10);
if ( currentNum == lastNum + 1 )
{
matches[matches.length-1] += String(currentNum);
}
else
{
if ( matches[matches.length-1].length > 1 )
{
matches.push(String(currentNum))
}
else
{ matches[matches.length-1] = String(currentNum);
}
}
});
matches = matches.filter(function(val){ return val.length > 1 }) //outputs ["6789", "123"]
DEMO
var numb = "5136789431235";
var matches = [""]; numb.split("").forEach(function(val){
var lastNum = 0;
if ( matches[matches.length-1].length > 0 )
{
lastNum = parseInt(matches[matches.length-1].slice(-1),10);
}
var currentNum = parseInt(val,10);
if ( currentNum == lastNum + 1 )
{
matches[matches.length-1] += String(currentNum);
}
else
{
if ( matches[matches.length-1].length > 1 )
{
matches.push(String(currentNum))
}
else
{ matches[matches.length-1] = String(currentNum);
}
}
});
matches = matches.filter(function(val){ return val.length > 1 }) //outputs ["6789", "123"]
document.body.innerHTML += JSON.stringify(matches,0,4);
Do you have to use Regex?
Not sure if the most efficient, but since they're always going to be numbers, could you split them up into an array of numbers, and then do an algorithm on that to sort through?
So like
var str = "123456";
var res = str.split("");
// res would equal 1,2,3,4,5,6
// Here do matching algorithm
Not sure if this is a bad way of doing it, just another option to think about
I've did something different on a fork from jquery.pwstrength.bootstrap plugin, using substring method.
https://github.com/andredurao/jquery.pwstrength.bootstrap/commit/614ddf156c2edd974da60a70d4945a1e05ff9d8d
I've created a string containing the sequence ("123456789") and scanned the sequence on a sliding window of size 3.
On each scan iteration I check for a substring of the window on the string:
var numb = "5136789431235";
//check for substring on 1st window => "123""
"5136789431235"
ˆˆˆ

How do I square a number's digits?

How do I square a number's digits? e.g.:
square(21){};
should result in 41 instead of 441
This is easily done with simple math. No need for the overhead of string processing.
var result = [];
var n = 21;
while (n > 0) {
result.push(n%10 * n%10);
n = Math.floor(n/10);
}
document.body.textContent = result.reverse().join("");
In a loop, while your number is greater than 0, it...
gets the remainder of dividing the number by 10 using the % operator
squares it and adds it to an array.
reduces the original number by dividing it by 10, dropping truncating to the right of the decimal, and reassigning it.
Then at the end it reverses and joins the array into the result string (which you can convert to a number if you wish)
I think he means something like the following:
var output = "";
for(int i = 0; i<num.length; i++)
{
output.concat(Math.pow(num[i],2).toString());
}
I believe this is what the OP is looking for? The square of each digit?
var number = 12354987,
var temp = 0;
for (var i = 0, len = sNumber.length; i < len; i += 1) {
temp = String(number).charAt(i);
output.push(Number(temp) * Number(temp));
}
console.log(output);
Split the string into an array, return a map of the square of the element, and rejoin the resulting array back into a string.
function squareEachDigit(str) {
return str.split('').map(function (el) {
return (+el * +el);
}).join('');
}
squareEachDigit('99') // 8181
squareEachDigit('52') // 254
DEMO
function sq(n){
var nos = (n + '').split('');
var res="";
for(i in nos){
res+= parseInt(nos[i]) * parseInt(nos[i]);
}
return parseInt(res);
}
var result = sq(21);
alert(result)
You'll want to split the numbers into their place values, then square them, then concatenate them back together. Here's how I would do it:
function fn(num){
var strArr = num.toString().split('');
var result = '';
for(var i = 0; i < strArr.length; i++){
result += Math.pow(strArr[i], 2) + '';
}
return +result;
}
Use Math.pow to square numbers like this:
Math.pow(11,2); // returns 121

Number formatting remove numbers after dot add comma at thousands

Currently output 1844.6304
desired output - comma thousands trim after dot ( no rounding )
1,844
I was looking some time on forums and can't find a solution to solve both cases.
Try this:
function intWithCommas(x) {
return Math.floor(x).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Example:
> intWithCommas(1844.6304)
'1,844'
Its even simpler like this
var n = 1844.6304,
s = Math.floor(n).toLocaleString();
console.log(s); //"1,844"
alert(s);
Try this:
function toCommaInteger(number){
var result = "" + ~~number;
var length = result.length;
var limit = result[0] === "-" ? 1 : 0;
for(var i = length-3; i > limit; i-=3 ){
result = result.substring(0,i) + "," + result.substring(i,length);
length++;
}
return result;
}
toCommaInteger(123589.85315) => 123,589
toCommaInteger(-1289.15315) => -1,289
toCommaInteger(5) => 5

convert digital display format

quick question, I have some integrate variable in javascript, say: 123456, or 123456789, it can be any valid number. Now, I would like to convert the number to a string like "123,456" or "123,456,789". Does anyone have a good algorithm for this? Of course, it should work for any numbers. For example: for 2000 ---> 2,000; 123456--->123,456
Give this a shot.
var num = 12345678;
var str = num + ""; // cast to string
var out = [];
for (var i = str.length - 3; i > 0; i -= 3) {
out.unshift(str.substr(i, 3));
}
out.unshift(str.substr(0, 3 + i));
out = out.join(','); // "12,345,678"
in addition to the other excellent solution
var n = 999999
var s = n.toLocaleString()

Categories