TAGS :Viewed: 22 - Published at: a few seconds ago

[ Number formatting in JavaScript ]

I am trying to create a JS script to format numbers using , separator but something is going bad in the logic implementation.

I am changing values of arr1 here.

This is the JS code I am using this time -

<script>
var arr1 = [1,2,3,4,5,6,7];
arr1.reverse();
var i = 1;
var tempArr = new Array();
for( i; i <= arr1.length ; i++ ) {
    if( i%3 == 0 ) {
        tempArr[i-1] = arr1[i-1];
        tempArr[i] = ',';
        i++;
    }
    else {
        tempArr[i-1] = arr1[i-1];
    }
}
console.log(tempArr.reverse().join(''));
</script>

Expected Output `` Current WRONG Output

1,234           =>  ,234 
12,345          =>  1,345
123,456         =>  ,12,456
1,234,567       =>  ,23,567

Kindly let me know what I am doing wrong(logical part) in the snippet as I am learning coding this time.

Answer 1


You've completely forgotten to add the original number as well as the comma:

var arr1 = [1,2,3,4,5,6,7].reverse()
  , tempArr = [];
for (var i = 0; ++i <= arr1.length;) {
    tempArr[i-1] = arr1[i-1];
    if (i % 3 === 0) tempArr[i] = arr1[i++] + ',';
}
console.log(tempArr.reverse().join(''));

A more concise version:

function addCommas(str) {
    str = (str + '').split('');
    for (var i = str.length - 1; (i -= 3) > 0;) str[i] += ',';
    return str.join('');
}

Answer 2


This is a quick go-over, with notes:

var arr1 = [1,2,3,4,5,6,7];
arr1.reverse();
var tempArr = [];
for( var i = 0, l = arr1.length; i < l ; i++ ) {
    if( i % 3 == 0 && i != 0) {
        tempArr.push(',');
    }
    tempArr.push(arr1[i]);
}
console.log(tempArr.reverse().join(''));

First couple tweaks are just for speed - in a 'for' loop, don't compare an array length every iteration. Some browsers perform extremely poorly when you do that, because they re-calculate the length each time you check it. Also, since JS arrays are zero indexed, it's a little less confusing if you also start your loop at the zero index. Constructing arrays using new Array is slower than just using an array literal (the []).

Next few tweaks just simplified your code. If the number is a % 3, and it's not the first loop, put a comma in. In either case, add the number that is represented by that iteration in.

Let me know if that makes sense.

Answer 3


You simply forgot to append arr1[i] to ','

<script>
var arr1 = [1,2,3,4,5,6,7];
arr1.reverse();
var i = 1;
var tempArr = new Array();
for( i; i <= arr1.length ; i++ ) {
    if( i%3 == 0 ) {
        tempArr[i-1] = arr1[i-1];
        tempArr[i] = arr1[i] + ',';
        i++;
    }
    else {
        tempArr[i-1] = arr1[i-1];
    }
}
console.log(tempArr.reverse().join(''));
</script>

Anyway, I think it's better to count 'i' from 0

Answer 4


Update found another shorter version

var a = [1,2,3,4,5,6,7], b, r = [];

while( (b = a.splice(-3)).length > 0 ) {
    r.push( b.reverse().join('') );
}

console.log( r.reverse().join() );

Old answer

I tried to produce result with while loop .

var orgArray = [1,2,3,4,5,6,7 ],
    ar = orgArray.slice(0).reverse(), // slice(0) to duplicate an array
    temp = [] ;

while ( ar.length != 0 ){

    temp.push( ar.pop() ); 

    if (  ar.length && ( ar.length %3 == 0 )  ) {
        temp.push( ',' );
    }        

}

console.log(  temp.join('') );

What about using JavaScript 1.8 array reduce method

var orgArray = [1,2,3,4,5,6,7];

var temp2 = orgArray.reverse().reduce( function( o,n,i  ){

    if ( i && i%3 == 0 ){
        o.push(',');
    };

    return o.push(n) && o;

},[]);

console.log( temp2.reverse().join('') );

Both returns same results ..