Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 924
Maria Jeysingh Anbu Avatar asked Apr 25 '18 09:04

Maria Jeysingh Anbu


People also ask

Is localeCompare case sensitive?

localeCompare() enables case-insensitive sorting for an array.


2 Answers

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;}
like image 99
Narendra Jadhav Avatar answered Sep 17 '22 08:09

Narendra Jadhav


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

like image 35
muhsalaa Avatar answered Sep 19 '22 08:09

muhsalaa