I'm using React ant design table.
In that table I'm trying to sort with null values by using localeCompare
It shows Type error.
JSON
const data = [{
key: '1',
name: null,
age: 32,
}, {
key: '2',
name: 'Jim Green',
age: '32',
}, {
key: '3',
name: 'Joe Black',
age: 32,
}];
When I sort I'm getting error like:
TypeError: Cannot read property 'localeCompare' of null
I have full code on Code sand box
localeCompare() enables case-insensitive sorting for an array.
You can check if your value is null
then you can assign blank using pipe.
In your code you can do like this
{
title: "Name",
dataIndex: "name",
key: "name",
sorter: (a, b) => {
a = a.name || '';
b = b.name || '';
return a.localeCompare(b);
}
},
DEMO
const data = [{
key: '1',
name: null,
age: 32,
}, {
key: '2',
name: 'Jim Green',
age: '32',
}, {
key: '3',
name: 'Joe Black',
age: 32,
}];
console.log(data.sort((a,b)=>{
a= a.name||'';
b= b.name||'';
return a.localeCompare(b)
}));
.as-console-wrapper { max-height: 100% !important; top: 0;}
if you have ES2020, there is optional chaining
to prevent error by returning undefined instead of throwing error when evaluated value is nullish. You can use it like this
arr.sort((a,b) => a?.localeCompare(b))
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With