M
M
miniven2018-02-16 14:17:49
JavaScript
miniven, 2018-02-16 14:17:49

How to sort an array of elements in a React project?

The situation is this: there is an array of employees. It is stored in the application state. I bring it out in a simple list. But I need to be able to sort employees by department, by name and by position. But I also need the list to be displayed in this format:
f2v5BKH7AG6DE4pBVnv69NgLEAODBm.png
Accordingly, if the sorting is by departments, but the groups will be departments, etc. That is, the elements must first be grouped, and then displayed in groups on the page.
Tell me how to implement it? Do I need to transform the array into an object, or how should I do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Petrov, 2018-02-16
@miniven

Actually, the question already has an answer.
First, we group by the desired field, then we sort each group by the desired field.
The result of grouping at the output can be different. But here it’s quite suitable if in the end there is an object where the key is the name of the group, the value is the elements themselves (this is exactly how it _.groupByworks R.groupBy). Then we just go through this object and sort each group (again, map + sort \ sortBy from lodash \ ramda). Without them, it's a little more difficult.
And then output the values. We take all groups, by groups we render the list of the first level, for each group we take its elements and render the internal list.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question