【问题标题】:How do I sort a integer column ascending and descending?如何对整数列进行升序和降序排序?
【发布时间】:2021-08-24 10:00:30
【问题描述】:
const [customerList, setCustomerList] = useState([]); //store all that information of the database in a list
  //make an axios request to get information from database
  useEffect(() => {
    Axios.get("http://localhost:3001/customers").then((response) => {
      setCustomerList(response.data);
    });
  }, []);

  const [counterCount, setCounterCount] = useState(0);
  function sortCountCustomer() {
    const sortedCountCustomer = [...customerList];
    let sortCountVisit = counterCount;
    //check the current sortCount, if it is 2 then go back to 1, if not then increase by 1
    if (sortCountVisit === 2) {
      sortCountVisit = 1;
      setCounterCount(1);
    } else {
      sortCountVisit += 1;
      setCounterCount(sortCountVisit);
    }
    console.log(sortCountVisit);
    if (sortCountVisit < 3) {
      sortedCountCustomer.sort(function (x, y) {
        if (sortCountVisit === 1) {
          return x.counts_of_visit > y.counts_of_visit
            ? 0
            : x.counts_of_visit
            ? -1
            : 1;
        } else if (sortCountVisit === 2) {
          return x.counts_of_visit < y.counts_of_visit
            ? 0
            : x.counts_of_visit
            ? 1
            : -1;
        }
      });

      setCustomerList(sortedCountCustomer);
    }
  }

  function getCountArrow() {
    if (counterCount === 1) return "↑";
    return "↓";
  }

<th class="countheader" onClick={() => sortCountCustomer()}>
                        Counts of Visit {getCountArrow()}

我在整数列上有以下功能,但是当我单击标题计数访问时它不起作用。因此,当我单击具有不同整数值的访问计数标题列时,我的代码不起作用,想要将其排序为升序和降序。

【问题讨论】:

  • 排序代码还能运行吗?您在浏览器开发人员工具控制台中获得任何输出吗?我看到了sortCountCustomer 函数,但不是你怎么称呼它
  • @JaromandaX 嗨 Jaro 我在下面编辑了我的代码问题以显示 sortCountCustomer}> 访问计数 {getCountArrow()}
  • () =&gt; sortCountCustomer 不调用函数......它返回函数,这是你的意思吗?还是你的意思是() =&gt; sortCountCustomer()
  • @JaromandaX 好的,我在其中进行了编辑,但是我对整数值的排序不起作用所以我的列有几个整数。 5 7 9 2 13,我要按升序和降序排序
  • 而不是三元运算符,只是 return x.counts_of_visit - y.counts_of_visitreturn y.counts_of_visit - x.counts_of_visit 酌情 - 因为你的三元没有意义

标签: javascript node.js reactjs frontend backend


【解决方案1】:

虽然无法理解您的大部分代码。但是根据我对您面临的问题的有限理解,您可以尝试实现以下逻辑。

let arr = [
  { val: 5 },
  { val: 7 },
  { val: 9 },
  { val: 2 },
  { val: 13 }
];
//For sorting in ascending order
console.log(arr.sort((a, b) => a.val - b.val));
//For sorting in descending order
console.log(arr.sort((a, b) => b.val - a.val));

【讨论】:

  • ``` 返回 x.counts_of_visit - y.counts_of_visit ? 0:x.counts_of_visit ? -1:1; } else if (sortCountVisit === 2) { return y.counts_of_visit - x.counts_of_visit ? 0:x.counts_of_visit ? 1:-1; ```我需要为此改变我的逻辑
  • Sorry max,可以理解你所做的实现。我稍后会尝试以全新的方式检查您的代码。
猜你喜欢
相关资源
最近更新 更多
热门标签