Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!