Skip to content

How to Solve the Grouped by Commas Challenge in Javascript

The challenge

Finish the solution so that it takes an input n (integer) and returns a string that is the decimal representation of the number grouped by commas after every 3 digits.

Assume: 0 <= n < 2147483647

Examples:

1 -> "1" 10 -> "10" 100 -> "100" 1000 -> "1,000" 10000 -> "10,000" 100000 -> "100,000" 1000000 -> "1,000,000" 35235235 -> "35,235,235"
Code language: plaintext (plaintext)

The solution in Javascript

Option 1:

function groupByCommas(n) { return n.toLocaleString() }
Code language: JavaScript (javascript)

Option 2:

function groupByCommas(n) { return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); }
Code language: JavaScript (javascript)

Option 3:

function groupByCommas(n) { var s = n.toString(), r = []; s = reverse(s); for (var i = , l = s.length; i < l; i += 3) { r.push(s.substr(i, 3)); } return reverse(r.join(',')); } function reverse(s) { return s.split('').reverse().join(''); }
Code language: JavaScript (javascript)

Test cases to validate our solution

describe("Tests", () => { it("test", () => { Test.assertEquals(groupByCommas(1), '1'); Test.assertEquals(groupByCommas(10), '10'); Test.assertEquals(groupByCommas(100), '100'); Test.assertEquals(groupByCommas(1000), '1,000'); Test.assertEquals(groupByCommas(10000), '10,000'); Test.assertEquals(groupByCommas(100000), '100,000'); Test.assertEquals(groupByCommas(1000000), '1,000,000'); Test.assertEquals(groupByCommas(35235235), '35,235,235'); }); });
Code language: JavaScript (javascript)

See also  How to Install Lodash through Yarn for React
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x