V
V
Vlad Yanukovich2021-06-14 15:14:15
React
Vlad Yanukovich, 2021-06-14 15:14:15

How to sort using Select?

There is a task to sort cards using select and inside the underlying option.
The project is based on react.

So the question is, how to sort the cards alphabetically with the choice of the appropriate option?

Select code:

<select className="sort-select"> 
     <option className="option-item">Популярности</option>
      <option className="option-item">По цене</option>
       <option className="option-item">По алфавиту</option>
</select>


Here is the state in which there is a copy of the original state (there are already filter buttons)
const [filtered, setFiltered] = useState([])

The data comes from the server and looks like this:

{
    "items" : [
        {
            "id" : 1,
            "name": "Колбаски Барбекю",
            "img": "ссылка на фотохост",
            "pizza": true,
            "drink": false,
            "snacks": false,
            "new": true,
            "meat": true,
            "spicy": true
        },
        {
            "name": "Двойной цыпленок",
            "img": "ссылка на фотохост",
            "pizza": true,
            "drink": false,
            "snacks": false,
            "new": true,
            "meat": true,
            "spicy": false
        }, ...

I need to sort by the name field, if I understand correctly, however, when the sort() method is called, nothing happens and any option does not respond to the console when it is selected (first time working with select and option).

Please help me sort this out.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-06-14
@Vladislav6

Describe sorting options - property name plus its type:

const sortOptions = [
  { key: '...', type: '...' },
  { key: '...', type: '...' },
  ...
];

You make sorting functions, put them in an object, the keys will be the names of data types (values ​​of the type property from the sortOptions array):
const sortFunctions = {
  type1: (a, b) => ...,
  type2: (a, b) => ...,
  ...
};

Based on an array with sorting options, you collect select:
const [ sortIndex, setSortIndex ] = useState(0);
const onSortChange = e => setSortIndex(+e.target.value);

<select value={sortIndex} onChange={onSortChange}>
  {sortOptions.map((n, i) => <option value={i}>{n.key}</option>)}
</select>

Sort your data:
const sortedItems = useMemo(() => {
  const { key, type } = sortOptions[sortIndex];
  const f = sortFunctions[type];
  return [...items].sort((a, b) => f(a[key], b[key]));
}, [ items, sortIndex, sortFunctions ]);

https://jsfiddle.net/gfer4p1y/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question