Skip to content

Instantly share code, notes, and snippets.

@jzevin
Created April 29, 2020 01:42
Show Gist options
  • Save jzevin/c86ed5fe7a1188fd4483ceb4b4937e61 to your computer and use it in GitHub Desktop.
Save jzevin/c86ed5fe7a1188fd4483ceb4b4937e61 to your computer and use it in GitHub Desktop.
JavaScript one liner for adding commas to a number
`3343453545`.split('').sort(()=>-1).reduceRight((p,c,i)=>i&&i%3===0?p+=c+',':p+=c,'')
@jzevin
Copy link
Author

jzevin commented Apr 29, 2020

I was thinking how i could do this with one line ES-2016 syntax
Got any ideas or improvements?

here's the prettier version:

`3343453545`
  .split("")
  .sort(() => -1)
  .reduceRight((p, c, i) => {
    if (i && i % 3 === 0) {
      return p += c + ","
    } else {
      return p += c
    }
  }, '');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment