【问题标题】:How to make Lodash sortBy() to sort data to descending order?如何使 Lodash sortBy() 对数据进行降序排序?
【发布时间】:2021-08-21 16:04:46
【问题描述】:

在 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);
    },

【问题讨论】:

  • 作为升序排序后的替代快速解决方案,只需执行 array.reverse()
  • @SteveTomlin 甚至我也看到了这种生活黑客。但我正在寻找一个合法/适当的解决方案。这也有效。另外,当我这样做时,它会将数组移动到该元素不存在的位置。

标签: javascript vue.js sorting lodash


【解决方案1】:

您可以尝试使用 Lodash 的 orderBy 方法。对我来说就像一个魅力。

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 34 },
  { 'user': 'fred',   'age': 40 },
  { 'user': 'barney', 'age': 36 }
];
 
// Sort by `user` in ascending order and by `age` in descending order.
_.orderBy(users, ['user', 'age'], ['asc', 'desc']);
// => objects for [['barney', 36], ['barney', 34], ['fred', 48],

你可以在这里查看官方文档Lodash orderBy

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多