javascript、js數組排序、多條件數組排序


開發時經常遇到 排序問題, 比如

遇到 對數據進行 多條件排序

/**
     * 搜索表單
     * @typedef {Object} Condition
     * @property {string} key 關鍵字
     * @property {boolean} isAscending 是否升序
     */
    /**
     * 數組排序 (帶條件類型)
     * @param arr 原數據
     * @param {[Condition]} condition 條件列表
     * @returns {[]}
     */
    var fns = function (arr, condition) {
      /**
       * 開始排序
       * @param {object} itemA 對比值A
       * @param {object} itemB 對比值B
       * @param {[Condition]} condition 條件列表
       * @param {number} index 當前條件排序下標
       * @returns {number}
       */
      var sort = function (itemA, itemB, condition, index) {
        if (!condition[index]) return 0
        const { key, isAscending = true } = condition[index]
        const a = itemA[key]
        const b = itemB[key]
        if (a === b) {
          return sort(itemA, itemB, condition, index + 1)
        } else {
          return isAscending ? a - b : b - a
        }
      }
      return arr.sort((a, b) => {
        return sort(a, b, condition, 0)
      })
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM