1

I attempted to use condition to sort array by different fields:

 return source.sort((a, b) => {
      if (a.orderBy && b.orderBy) {
        return sortOrder === 'asc'
          ? a.orderBy - b.orderBy
          : b.orderBy - a.orderBy;
      }
      
      return sortOrder === 'asc' ? a.name - b.name : b.name - a.name;
      
    });

I have got the error:

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. 

What is problem?

It works for me, but probably it could be better:

  return source.sort((a, b) => {
      if (a.orderBy && b.orderBy) {
        return sortOrder === 'asc'
          ? a.orderBy - b.orderBy
          : b.orderBy - a.orderBy;
      }

      if (sortOrder === 'asc') {
        if (a.name < b.name) {
          return -1;
        }
        if (a.name > b.name) {
          return 1;
        }
        return 0;
      } else {
        if (a.name > b.name) {
          return -1;
        }
        if (a.name < b.name) {
          return 1;
        }
        return 0;
      }
    });
Hamed
  • 23
  • 4
  • 1
    What are the types of `orderBy`? You're trying to do subtraction with them, so they have to be one of the types listed in the error. – jnpdx Sep 02 '22 at 18:48
  • `orderBy` it is number type. `name` is string – Hamed Sep 02 '22 at 18:50
  • So, as you say, `name` is a `string` -- you're trying to do subtraction with it. That doesn't work. – jnpdx Sep 02 '22 at 18:51
  • Okay, how then? > < else? – Hamed Sep 02 '22 at 18:53
  • 1
    You can use [localeCompare](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare) to compare strings. -> `return a.name.localeCompare(b.name);` – Reyno Sep 02 '22 at 18:57
  • Please provide a [mre] that demonstrates your issue and only your issue when pasted, as-is, into a standalone IDE. Right now you haven't defined `source`, so I can't reproduce your problem. – jcalz Sep 02 '22 at 18:57
  • I already added into question – Hamed Sep 02 '22 at 18:58

1 Answers1

1

You cannot substract strings. You should use a.prototype.localeCompare(b)

It will return 1 if a > b; -1 if b > a; and otherwise 0

In your example you should do following:

return source.sort((a, b) => {
  if (a.orderBy && b.orderBy) {
    return sortOrder === "asc" ? a.orderBy - b.orderBy : b.orderBy - a.orderBy;
  }

  return sortOrder === "asc" ? a.localeCompare(b) : b.localeCompare(a);
});
Hostek
  • 509
  • 3
  • 9