How to make Lodash sortBy() to sort data to descending order?

Viewed 5087

sortBy() in Lodash isn't sorting to the descending order, when I pass 'desc', when calling the function as const sortedData = _.sortBy(data, ['rawAvgPrice'], ['desc']);. This works fine with the ascending order. But not with the descending order. I have posted the sorting functionality which I have written. I read the thread "lodash multi-column sortBy descending" but it didn't help me with my problem. Therefore decided to post this.

    /**
     * @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);
    },
2 Answers

From the lodash documentation we find this when searching for _.sortBy: "Creates an array of elements, sorted in ascending order by the results of running each element in a collection thru each iteratee. "

From that we can see that _.sortBy will always return an sorted array in ascending order.

What you can try is to use _.orderBy instead like this: _.orderBy(users, 'age', 'desc');

You can try using the Lodash's orderBy method. Worked like a charm for me.

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],

You can check the official documentation here Lodash orderBy

Related