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

開發時常常遇到 排序問題, 好比數組

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

/** * 搜索表單 * @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) }) }
相關文章
相關標籤/搜索