代码之家  ›  专栏  ›  技术社区  ›  rosu alin

react js sort by quantity>和<都返回相同的结果[重复]

  •  -1
  • rosu alin  · 技术社区  · 6 年前

    这是我的代码:

    const-sorteddiscounts=counts.sort((a,b)=>a.quantity>b.quantity);
    const amountSortedDiscounts=折扣
    .map(el=>el.数量)
    .concat(数量+0.5)
    .sort((a,b)=>a.数量>b.数量);
    const amountSortedDiscounts2=amountSortedDiscounts.sort(
    (a,b)=>a.数量<b.数量
    )(二)
    const index=amountSortedDiscounts2.indexof(数量+0.5)-1;
    < /代码> 
    
    

    amountSortedDiscounts和amountSortedDiscounts2是相同的,即使是tho'1也是按a.quantity>b.quantity排序的,后者是按a.quantity<b.quantity排序的。

    我在这方面做了什么错事?

    < H1>编辑:

    这就是我困惑的地方: 这两者返回相同的顺序:

    const-sorteddiscounts=counts.sort((a,b)=>a.quantity>b.quantity);
    const-sorteddiscounts2=折扣。排序((a,b)=gt;a.数量<b.数量);
    < /代码> 
    
    

    试图弄明白为什么它们都是一样的

    . 2答

    这是我的代码:

    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都是相同的,即使是tho'1也是按a.quantity > b.quantity后者按a.quantity < b.quantity

    我在这方面做了什么错事?

    enter image description here

    编辑:

    这就是我困惑的地方: 这两者返回相同的顺序:

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

    试图弄明白为什么它们都是一样的

    2 回复  |  直到 6 年前
        1
  •  1
  •   Shahram    6 年前

    这是错误的比较。

    ASC(升序):

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

    描述(降序):

    const sortedDiscounts = discounts.sort((a, b) => b.quantity - a.quantity);
    
        2
  •  2
  •   kopiro    6 年前

    如果你要处理数字,就用 a.quantity - b.quantity 相反。

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