如何使用 Lodash 的 sortBy() 方法将数据按降序排序?

23
在Lodash中,当我传递'desc'时,sortBy()无法按降序排序,当我调用函数时const sortedData = _.sortBy(data, ['rawAvgPrice'], ['desc']);。这对于升序排序可以正常工作,但对于降序排序不起作用。我已发布了我编写的排序功能。我阅读了“ lodash多列sortBy降序”线程,但它没有帮助我解决问题。因此决定发布这个问题。
    /**
     * @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()。 - Steve Tomlin
@SteveTomlin,我也看到了这个技巧。但我正在寻找一个合法/适当的解决方案。这个也可以用。而且当我这样做时,它会移动数组,使得该元素不存在。 - Nine3KiD
3个回答

42

lodash文档中可以找到以下内容,当我们搜索_.sortBy时:“通过对集合中的每个元素运行每个迭代器的结果,按升序创建一个元素数组。”

从中我们可以得出结论,_.sortBy将始终返回一个按升序排序的数组。

你可以尝试使用_.orderBy来进行排序,例如:

_.orderBy(users, 'age', 'desc');

11

你可以尝试使用 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

4
另一个在这里没有提到的选项是只需对结果进行.reverse()

const users = [{
    'user': 'alice',
    'age': 48
  },
  {
    'user': 'bob',
    'age': 34
  },
  {
    'user': 'claire',
    'age': 40
  },
  {
    'user': 'dennis',
    'age': 36
  }
];

console.log(_.sortBy(users, 'age').reverse());
<script src="https://unpkg.com/lodash@4.17.21/lodash.js"></script>


需要注意的是,如果您需要一种稳定的排序方式,以保留除指定属性以外的现有顺序,则此方法将无法实现。 - eclux

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接