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.

4
  • Check my answer here stackoverflow.com/questions/16037165/… Commented May 21, 2013 at 6: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 Commented May 21, 2013 at 6:08
  • 1
    Your logic is correct but you are replacing the number with ',' .. You should concat the number and ',' Commented May 21, 2013 at 6:15
  • 1
    @PrasathK ohh yeah ..thx for pointing me in the correct direction :) upvoted your comment :) Commented May 21, 2013 at 6:18

4 Answers 4

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('');
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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

Comments

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

2 Comments

@Trialcoder jsperf cases are while loop, reduce, correct answer
thx for the link +1 :) so it means reduce is taking less time..I am not sure as I m new to this tool

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.