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?

ksenia
  • 187
  • 7
  • 23
  • 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. – Charlie Bamford Jun 02 '21 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 })` – adiga Jun 02 '21 at 17:39
  • @adiga thank you, that almost worked. I don't think it supports numbers then. and I have those as well – ksenia Jun 02 '21 at 17:48
  • Please add the sample data for `list` with `col` properties. – adiga Jun 02 '21 at 17:49
  • 2
    You could use `String(a[col])` and `String(b[col])`. Or `a[col].toString()` – adiga Jun 02 '21 at 17:50
  • I meant I am trying to use the same function to filter a column that is all numbers -> name column is all strings (with numbers), but let's say age is all numbers [13, 45, 76] – ksenia Jun 02 '21 at 17:51

0 Answers0