zoukankan      html  css  js  c++  java
  • JavaScript双重排序

    前言:正好这两天正在做一个功能,需要在前台进行排序展示,因为是动态的,后台排序不能搞定,只能咋前台通过JS来进行排序展示,所以我们用sort()来解决这个问题,sort不仅能给数组,对象,集合进行简单的排序,还能进行双重,多重排序。哈哈.... 不讲废话了

    JavaScript双重排序

    1. 语法详解

      Array.sort((a, b) =>{})

      JS中sort 函数需要传入一个函数,例如 sort((a,b)=>{ }). a, b 为需要排序的数组的两个值,可以根据x, y的大小进行返回:

      负值,如果所传递的第一个参数比第二个参数小。

      零,如果两个参数相等。

      正值,如果第一个参数比第二个参数大。

    2. 示例

     1 sortName(sortObj){
     2     // this.addOrderData.product_list.sort(this.compare(sortObj.prop, sortObj.order))
     3     this.addOrderData.product_list.sort((a, b)=>{
     4  
     5         if (sortObj.order == 'ascending') {
     6             if (a["product_name"] === b["product_name"]) {
     7                 return a["lot"] > b["lot"] ? 1 : a["lot"] < b["lot"] ? -1 : 0;
     8             } else {
     9                 return a["product_name"] > b["product_name"] ? 1 : -1;
    10             }
    11         }else {
    12             if (a["product_name"] === b["product_name"]) {
    13                 return a["lot"] > b["lot"] ? 1 : a["lot"] < b["lot"] ? -1 : 0;
    14             } else {
    15                 return a["product_name"] < b["product_name"] ? 1 : -1;
    16             }
    17         }
    18  
    19     })
    20  
    21 }

    Js中sort 函数需要传入一个函数,例如 sort(function(x,y){ }). x, y 为需要排序的数组的两个值,可以根据x, y的大小进行返回:

    负值,如果所传递的第一个参数比第二个参数小。

    零,如果两个参数相等。

    正值,如果第一个参数比第二个参数大。

     

    3.注意事项

    在IE中JS不支持Array.sort((a, b) =>{})可换成Array.sort(function(a, b) {})

  • 相关阅读:
    2020牛客寒假算法基础集训营3
    2020牛客寒假算法基础集训营2
    2020牛客寒假算法基础集训营1
    Educational Codeforces Round 81 + Gym 102267
    博客迁移到自己的WordPress站上
    HDU 5172 GTY's gay friends 线段树 or Hash
    HDU 3436 Queue-jumpers Splay
    HDU 1890 Robotic Sort Splay
    POJ 3468 A Simple Problem with Integers Splay
    BZOJ 1503 郁闷的出纳员 Splay
  • 原文地址:https://www.cnblogs.com/JamelAr/p/12011444.html
Copyright © 2011-2022 走看看