L
L
LaranceXF2021-07-26 16:29:46
React
LaranceXF, 2021-07-26 16:29:46

How to sort an array in reverse order?

Hello everyone, how to sort an array from a-z and from z-a by clicking on the same button. Now the reverse is not possible.

https://codesandbox.io/s/peaceful-khorana-gbfed

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-07-26
@LaranceXF

const [ sort, setSort ] = useState(false);

const sorted = useMemo(() => {
  return [...data].sort((a, b) => {
    return a.name.localeCompare(b.name) * (sort ? -1 : 1);
  });
}, [ sort ]);

<button onClick={() => setSort(sort => !sort)}>Сортировать</button>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question