Sorting antd column having multiple values

Viewed 992

I have a column in my antd table called Specialities. The data(**specialities**) in that column is coming from back end as an array collection.

enter image description here

enter image description here

What I tried to do is

{
    title: 'Specialties',
    dataIndex: 'specialties',
    key: 'specialties',
    sorter: (a, b) => a.specialties.localeCompare(b.specialties),
    render: (val, record)=><div title={val} className="text_overlap">{val.map((a)=>a.name).toString()}</div>
}

I get this error while doing this

TypeError: a.specialties.localeCompare is not a function

How can I sort this column where data is coming from an array collection?

3 Answers

You can use localCompare, but on the field name in the object

const data = {
  foo: "bar",
  specialities: [
    {name: 'Medical'},
    {name: 'Cooking'},
    {name: 'Telemetry'}
  ]
}
data.specialities.sort((a, b) => a.name.localeCompare(b.name));
console.log(data)

In your object, you specify the key, so just need to specify the field

{
    title: 'Specialties',
    dataIndex: 'specialties',
    key: 'specialties',
    sorter: (a, b) => a.name.localeCompare(b.name),
    render: (val, record)=><div title={val} className="text_overlap">{val.map((a)=>a.name).toString()}</div>
}

The localeCompare only works on string type.

You need to compare on name field of the localeCompare

sorter: (a, b) => a.name.localeCompare(b.name)

If you want to add sort methods for all the columns, you can set sortDirections: ['ascend' | 'descend'] on table props.

If you want to sort according to each column name you need to concat the names in any row.

sorter: (a, b) => {
  return a
    .specialities
    .map((g) => g.name)
    .join("")
    .localeCompare(b.specialities.map((h) => h.name).join(""));
},

Live example:

Edit wizardly-shadow-7nv54

Related