首页 > 解决方案 > 如何使 Lodash sortBy() 对数据进行降序排序?

问题描述

Lodash 中的 sortBy() 没有按降序排序,当我传递 'desc' 时,调用函数为const sortedData = _.sortBy(data, ['rawAvgPrice'], ['desc']);. 这适用于升序。但不是降序排列。我已经发布了我编写的排序功能。我阅读了线程“ lodash multi-column sortBy descending ”,但它对我的问题没有帮助。因此决定发布这个。

    /**
     * @param {String} element - sorting object element name.
     * @param {String} dir - the direction of the sort ASC/DESC.
     * @param {Boolean} flag - Signaling to sort the table and update.
     */
    sortTableNew(element, dir, flag) {
      let direction = dir;
      
      // Change the sorting from ASC to DESC/ DESC to ASC
      if (flag) {
        direction = dir === 'asc' ? 'desc' : 'asc';
      }
      
      // Getting the current open tabs details
      const { activeTab } = this.$props.state.keywordSearch;
      const { data } = this.$props.state.keywordSearch.tabs[activeTab];

      const sortedData = _.sortBy(data, [element], [direction]);
      
      // Updating the cache to dispatch data to the table
      cachedHelper.updateCacheKeyword(cachedHelper.SCREEN_TYPE.keywordSearch, activeTab, sortedData);
      cachedHelper.updateCacheSortType(cachedHelper.SCREEN_TYPE.keywordSearch, activeTab, direction, column);
    },

标签: javascriptvue.jssortinglodash

解决方案


lodash 文档中,我们在搜索时发现_.sortBy:“创建一个元素数组,按通过每个迭代器运行集合中每个元素的结果按升序排序。”

从中我们可以看到,它_.sortBy总是会返回一个升序排序的数组。

您可以尝试_.orderBy像这样使用: _.orderBy(users, 'age', 'desc');


推荐阅读