reactjschartist.js

Add thousand separators to chartist.js


So I'm trying to add thousand separators to graph numbers, made with npm package chartist. The way I'm trying to implement that is next:


    const data = {
          // A labels array that can contain any sort of values
          labels: this.props.labels.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."),
          // Our series array that contains series objects or in this case series data arrays
          series: [this.props.data]
        };

I tried to change the package itself but every time I get the next error:


    Uncaught TypeError: Cannot assign to read only property 'length' of object '[object String]'
        at String.push (<anonymous>)
        at Object.Chartist.normalizeData (chartist.js:400)
        at constr.createChart (chartist.js:3387)
        at constr.initialize (chartist.js:1940)

Also I tried to implement this as a function:


    function(label){label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");}

But then it's showing that data.labels(from the npm package) is not a function.

EDIT 1: If I console.log(this.props.labels) then I get this log in console The graph numbers I pasted there with a package names chartist-plugin-tooltips, so maybe I have to change something there, I don't know.


Solution

  • It's trying to run .push against a String, instead of an array. I assume that labels should be an array, but .replace is going to return a string.

    Perhaps you intended to convert your labels back to an array using .split(). From toString() you will have a string that is a comma-separated list of your array values. So you will have to split it again using the commas. For example

    labels: this.props.labels.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".").split(',')
    

    Edit

    If your array values have commas, you will need to use a different separator with .join, instead of .toString.

        this.props.labels.join('$').replace(/\B(?=(\d{3})+(?!\d))/g, ".").split('$')
    

    Final edit

    If you are not actually adding values to the array, it would be much cleaner to map through the elements! I realised this a bit late when I read your question again.

    this.props.labels.map(label => label.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."))