Home  >  Forum  >  Angular
Post New Query

sort numeric columns



Asked on May 22, 2019
Hello,

I have following method which sorts only string columns and not the numeric columns. 
setSorting(sorting: DataSorting): void {
        this._sorting = sorting;

        if (sorting && sorting.key) {
            this._rows.sort((a: DataRow, b: DataRow) => {
                let left = a.getValue(sorting.key);
                if (left) {
                    left = (left instanceof Date) ? left.valueOf().toString() : left.toString();
                } else {
                    left = '';
                }

                let right = b.getValue(sorting.key);
                if (right) {
                    right = (right instanceof Date) ? right.valueOf().toString() : right.toString();
                } else {
                    right = '';
                }

                return sorting.direction === 'asc'
                    ? left.localeCompare(right)
                    : right.localeCompare(left);
            });
        }
    }

But I want to sort numeric columns also. How to achieve this?
Can anyone please provide solution for this?

Thanks & Regards,
Shilpa Kulkarni



Replied on May 27, 2019
I have modified the above function as follows:

setSorting(sorting: DataSorting): void {
this._sorting = sorting;

if (sorting && sorting.key) {
this._rows.sort((a: DataRow, b: DataRow) => {
let left = a.getValue(sorting.key);
if (left) {
if (this.checkNumber(left) === "true") {
left = left.toString();
}else{
left = (left instanceof Date) ? left.valueOf().toString() : left.toString();
}
} else {
left = '';
}

let right = b.getValue(sorting.key);
if (right) {
if (this.checkNumber(left) === "true") {
right = right.toString();
} else {
right = (right instanceof Date) ? right.valueOf().toString() : right.toString();
}
} else {
right = '';
}

return sorting.direction === 'asc'
? left.localeCompare(right)
: right.localeCompare(left);
});
}
}



private checkNumber(charStr:any){
if(isNaN(charStr)){
    console.log(charStr + " is not a number <br/>");
return "false";
}else{
    console.log(charStr + " is a number <br/>");
return "true";
}

Here I am checking whether the value is number or not in checkNumber()method.
If it is number I am trying to sort it numerically as follows:
left = left.toString();
But it is not sorting as numeric it still sorts as string . Can you please help me to solve this issue?



Write Answer







©2019 concretepage.com | Privacy Policy | Contact Us