最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React | localeCompare sort with null values - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a comment  | 

2 Answers 2

Reset to default 12

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

发布评论

评论列表(0)

  1. 暂无评论