1
votes

I am using html-table to show data. There is a column named Charges in my table, which shows currency in US format. The data is coming from the array collection patientsSearchData. (I want to sort Charges ascending and descending while clicking an icon )

Sample column format

enter image description here

 new Intl.NumberFormat('en-USD', { currency: 'USD', style: 'currency' }).format(Number(Item.Charges))

The above code is used for USD format.

Charges are coming from array in string format

Eg:

var charges =["1,416.20", "807.21", "42.82", "187.17"]

The sort I applied is:

sort(event) {
        const {patientsSearchData } = this.state;
        const { SearchList } = this.props;
        var search = [];
        if (SearchList.length == 0) {
                search = _.orderBy(patientsSearchData, (o) => typeof o[event.target.id] === 'string' ? o[event.target.id].trim().toLowerCase() : o[event.target.id], order[event.target.id] ? 'asc' : 'desc');
                this.setState({
                orderby: event.target.id,
                patientsSearchData: search,
            });
        }

After sorting (in ascending order), and applying USD format, what it looks like in the html-table is shown below:

$1,416.20

$187.17

$42.82

$807.21

What actually I need is:

$42.82

$187.17

$807.21

$1,416.20

1
Is it possible to sort before you format? Then you can just arr.map(Number).sort((a,b)=>(a-b)*direction) where direction is 1 for ascending and -1 for descending. - HMR
My array collection contains other fields such as Name, Address etc , which are string fields . So is it possible to sort the entire html-table using arr.map(Number).sort((a,b)=>(a-b)*direction) ? - Jane Fred

1 Answers

1
votes

I did one more checking in the sort function that if the value in array contains only number or decimal points.

else if (event.target.id === 'Charges'){
                search = _.orderBy(patientsSearchData, (o) => o[event.target.id].match(/^\d+(\.\d+)?$/) ? Math.floor(o[event.target.id]) : o[event.target.id], order[event.target.id] ? 'asc' : 'desc');
            }