Search code examples
javascriptjqueryarrayssortingtogglebutton

How can i make a click button when do i click make sort(a-b) array and then click again to sort(b-a)


Here is my question How can i make a click button when do i click make array.sort(x-y) and then click again to make array.sort(y-x)

i'm already have the function but i'm confuse how to do it...

let me clarify my question: when do i click on button i make sort to array from bigger to smaller number and then i would like to press on the same button to make the array sort from smaller to bigger

here is my code:

$(".lower").click(() => {
    colorsValueMenu("highest", "spot", "gainers", "losers", "lower")
    highest = arrayCoinsD.sort(function (a, b) { return b.quote.USD.percent_change_24h - a.quote.USD.percent_change_24h })
    createCoinDiv(arrayCoinsD, arrayCoinsI)
    $(".lower").click(() => {
        colorsValueMenu("lower", "spot", "gainers", "losers", "highest")
        lower = arrayCoinsD.sort(function (a, b) { return a.quote.USD.percent_change_24h - b.quote.USD.percent_change_24h })
        createCoinDiv(arrayCoinsD, arrayCoinsI)
    })
})

it's work but just on the first & second time... i want to make it like toggleClass action for every single click


Solution

  • You should make your code DRY (Don't Repeat Yourself)

    You can create a flag and change the operations as per the flag as:

    let flag = "high";
    
    $(".lower").click(() => {
      //   Highest
      colorsValueMenu(
        flag === "high" ? "highest" : "lower",
        "spot",
        "gainers",
        "losers",
        "lower"
      );
      highest = arrayCoinsD.sort(function (a, b) {
        return flag === "high"
          ? b.quote.USD.percent_change_24h - a.quote.USD.percent_change_24h
          : a.quote.USD.percent_change_24h - b.quote.USD.percent_change_24h;
      });
    
      createCoinDiv(arrayCoinsD, arrayCoinsI);
      flag = flag === "high" ? "low" : "high";
    });