Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda