Search code examples
javascriptvue.jssortinglodash

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


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

Solution

  • 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');