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
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
Share Improve this question asked Apr 25, 2018 at 9:24 Maria Jeysingh AnbuMaria Jeysingh Anbu 3,3123 gold badges37 silver badges58 bronze badges2 Answers
Reset to default 12You 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