i have an function, which looks like this:
const [data, setData] = useState([]);
const [sortType, setSortType] = useState("title");
useEffect(() => {
const sortArray = (type) => {
const types = {
title: "title",
release_date: "release_date",
charactersList: "charactersList",
};
const sortProperty = types[type];
if (sortProperty === "charactersList") {
const sorted = [...episodes].sort(
(a, b) => a.charactersList.length - b.charactersList.length
);
setData(sorted);
} else {
const sorted = [...episodes].sort((a, b) =>
("" + a[sortProperty]).localeCompare("" + b[sortProperty])
);
setData(sorted);
}
};
sortArray(sortType);
}, [episodes, sortType]);
and the select:
<select defaultValue="Sort" onChange={(e) => setSortType(e.target.value)}>
<option value="title">Alfabetycznie A-Z</option>
<option value="release_date">wg. daty rosnąco</option>
<option value="charactersList">wg. liczby postaci rosnąco</option>
</select>
I was wondering,how can i change it, so i could choose an option of value="titleDESC" so that it would sort DESC?
You can use a sort function with an identified direction of sorting?
function sortTitle(a, b, d) {
return a.localeCompare(b) * d;
}
Which you can call from your array.sort() like so:
array.sort((a,b) => sortTitle(a,b,-1))
see this stackblitz: https://stackblitz.com/edit/js-ubeyxc
If you make the call value of d to be contingent on titleDESC or titleASC you can use the same sorting function, just change the direction of the sorting.
const d = (sortProperty==='titleDESC') ? -1 : 1;
array.sort((a,b) => sortTitle(a,b,-1));