简体   繁体   中英

How to use condition in sort function?

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;
      }
    });

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM