Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
How can i change my sort function to both accept ascending order and descending order

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda