简体   繁体   中英

React | localeCompare sort with null values

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM