2

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.

Trialcoder
  • 5,816
  • 9
  • 44
  • 66
  • Check my answer here http://stackoverflow.com/questions/16037165/displaying-a-number-in-indian-format-using-javascript/16037650#16037650 – Prasath K May 21 '13 at 06:07
  • @PrasathK Thx but I am learning coding part so really interested in knowing the wrong part in my code..will look at urs too – Trialcoder May 21 '13 at 06:08
  • 1
    Your logic is correct but you are replacing the number with ',' .. You should concat the number and ',' – Prasath K May 21 '13 at 06:15
  • 1
    @PrasathK ohh yeah ..thx for pointing me in the correct direction :) upvoted your comment :) – Trialcoder May 21 '13 at 06:18

4 Answers4

4

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('');
}
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
3

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.

Stephen
  • 5,362
  • 1
  • 22
  • 33
  • 1
    Not a problem. I forgot to mention as well that since JS arrays are dynamically sizing, using 'push' to just keep adding on the elements is one less place where you'll forget a "-1" or something.. and possibly save a few hairs on your head from frustration. – Stephen May 21 '13 at 06:25
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

Dinever
  • 690
  • 5
  • 13
2

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

rab
  • 4,134
  • 1
  • 29
  • 42