0

I have a sort function that sorts yard names (which arte strings) alphabetically.

const sortList = (list, col) => {
    return list.sort((a, b) => {
        if (!b[col] && !a[col])
            return 0
        if (!a[col])
            return -1
        if (!b[col])
            return 1
        if (a[col] < b[col])
            return -1
        if (a[col] > b[col])
            return 1
        else return 0
    })
};

However sometimes, the yards have number in them and the sorting looks like this: enter image description here

I have tried adding attr to a[col] and b[col] but it produced even weirder results. Is there an idea on how to avoid this type of behaviour?

6
  • Can you give examples of other ways the yards are named? Right now, I would suggest ParseInt(a[col].substr(5)); To just get the number, but I'm guessing that's not going to fix your problem. Commented Jun 2, 2021 at 17:37
  • 3
    You can remove the last 2 if and if-else blocks and replace it with: return a[col].localeCompare(b[col], undefined, { numeric: true }) Commented Jun 2, 2021 at 17:39
  • @adiga thank you, that almost worked. I don't think it supports numbers then. and I have those as well Commented Jun 2, 2021 at 17:48
  • Please add the sample data for list with col properties. Commented Jun 2, 2021 at 17:49
  • 2
    You could use String(a[col]) and String(b[col]). Or a[col].toString() Commented Jun 2, 2021 at 17:50

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.