【问题标题】:React JS Sort by quantity > and < both return the same result [duplicate]React JS按数量排序>和<都返回相同的结果[重复]
【发布时间】:2019-04-29 01:40:20
【问题描述】:

这是我的代码:

const sortedDiscounts = discounts.sort((a, b) => a.quantity > b.quantity);
const amountSortedDiscounts = discounts
.map(el => el.quantity)
.concat(quantity + 0.5)
.sort((a, b) => a.quantity > b.quantity);
const amountSortedDiscounts2 = amountSortedDiscounts.sort(
(a, b) => a.quantity < b.quantity
);
const index = amountSortedDiscounts2.indexOf(quantity + 0.5) - 1;

amountSortedDiscounts 和amountSortedDiscounts2 相同,即使'1 按a.quantity &gt; b.quantity 排序,后者按a.quantity &lt; b.quantity 排序

我在排序中做错了什么?

编辑:

这让我感到困惑: 这两者都返回相同的订单:

const sortedDiscounts = discounts.sort((a, b) => a.quantity > b.quantity);
const sortedDiscounts2 = discounts.sort((a, b) => a.quantity < b.quantity);

试图弄清楚为什么它们都相同

【问题讨论】:

  • a.quantity &gt; b.quantity 这不是一个有效的排序比较函数。
  • 还有Array.sort,它不会先复制数组,你会想要克隆数组然后排序。
  • 谢谢,我理解的数字,但还有一个问题。这个:const sortedDiscounts = discounts.sort((a, b) =&gt; a.quantity &gt; b.quantity); 和这个 const sortedDiscounts = discounts.sort((a, b) =&gt; a.quantity &lt; b.quantity); 也返回相同的对象数组。这是为什么?是否与@Keith 第二条评论有关?
  • @rosualin 阅读了我链接的欺骗...

标签: javascript reactjs sorting indexof


【解决方案1】:

如果您要处理数字,请改用a.quantity - b.quantity

查看排序的工作原理: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

【讨论】:

    【解决方案2】:

    这是错误的比较。

    ASC(升序):

    const sortedDiscounts = discounts.sort((a, b) => a.quantity - b.quantity);
    

    DESC(降序):

    const sortedDiscounts = discounts.sort((a, b) => b.quantity - a.quantity);
    

    【讨论】:

    • 谢谢,掌握了这个窍门。我现在正在测试所有案例并让您知道这是否有效
    • @rosualin 请记住,在对数组进行排序时,您正在对原始数组进行排序并存储为常量。我的意思是排序会影响原始数组。如果您不想对原始文件进行排序而只在 sortedDiscounts 中排序,那么您可以试试这个:code: const sortedDiscounts = [...discounts].sort((a, b) =&gt; a.quantity - b.quantity);
    猜你喜欢
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2020-01-28
    • 2019-04-30
    相关资源
    最近更新 更多