Search code examples
javascriptobjectkeyreduceinsertion-order

Javascript - grouping an array and then sorting the grouped result based on length


this is the array ;

var dataArr = [
  {
    "permalink": /* link*/
      "subreddit": "mac"
  }, {
    "permalink": /* link*/
      "subreddit": "worldnews"
  }, {
    "permalink": /* link*/
      "subreddit": "MushroomGrowers"
  }, {
    "permalink": /* link*/
      "subreddit": "chrome"
  }, {
    "permalink": /* link*/
      "subreddit": "onions"
  }, {
    "permalink": /* link*/
      "subreddit": "onions"
  }, {
    "permalink": /* link*/
      "subreddit": "SquaredCircle"
  }.....
]

grouping seems simple enough based on the "subreddit" key using underscore

const grouped = _.groupBy( dataArr, 'subreddit' )

returns an object something like this

{
  ArtisanVideos: [
    {
      "permalink": ' link ',
      subreddit: "ArtisanVideos"
    },
    {
      "permalink": ' link ',
      subreddit: "ArtisanVideos"
    },
    {
      "permalink": ' link ',
      subreddit: "ArtisanVideos"
    }
  ],
  chrome: [
    {
      "permalink": ' link ',
      subreddit: "chrome"
    }
  ],
  laravel: [
    {
      "permalink": ' link ',
      subreddit: "laravel"
    },
    {
      "permalink": ' link ',
      subreddit: "laravel"
    },
    {
      "permalink": ' link ',
      subreddit: "laravel"
    }
  ],
  mac: [
    {
      "permalink": ' link ',
      subreddit: "mac"
    }
  ]
}

Now, how do I sort the grouped objects based on the length of the array


Solution

  • From my above comment ...

    "In case the OP depends on key insertion order (though it would even work) of an object (because this is what the OP is asking for) then the OP's entire data handle approach is at question. What one could do instead ... create a sorted array of object-items from the former object of grouped entries."

    The next provided solution does exactly what already got proposed.

    In order to achieve the intermediate grouping goal one would reduce the given data-structure into an object of grouped entries (each entry holding an array of some of the former data-array items.

    Each of the entries now can be mapped into an own object of the still unsorted result array which within a last step will be sorted by either each object's sole array-value length-property or by a locale comparison of the single property names (keys).

    function groupAndCollectBySameKeyValue({ key, result }, item) {
      const groupValue = item[key];
      (result[groupValue] ??= []).push(item);
      return { key, result };
    }
    
    var dataArr = [
      { permalink: 'link', subreddit: 'laravel' },
      { permalink: 'link', subreddit: 'mac' },
      { permalink: 'link', subreddit: 'ArtisanVideos' },
      { permalink: 'link', subreddit: 'laravel' },
      { permalink: 'link', subreddit: 'ArtisanVideos' },
      { permalink: 'link', subreddit: 'chrome' },
      { permalink: 'link', subreddit: 'ArtisanVideos' },
      { permalink: 'link', subreddit: 'laravel' },
    ];
    console.log(
      dataArr
        .reduce(groupAndCollectBySameKeyValue, {
          key: 'subreddit',
          result: {},
        })
        .result
    );
    console.log(
      Object
        .entries(
          dataArr
            .reduce(groupAndCollectBySameKeyValue, {
              key: 'subreddit',
              result: {},
            })
            .result
        )
        // create object from grouped entry (key-value pair).
        .map(([key, value]) => ({ [key]: value }))
        .sort((a, b) =>
          // ... either by array length ...
          Object.values(b)[0].length - Object.values(a)[0].length
          // ... or by locale alphanumeric precedence.
          || Object.keys(a)[0].localeCompare(Object.keys(b)[0])
        )
    );
    .as-console-wrapper { min-height: 100%!important; top: 0; }

    One of cause can achieve the OP's original goal as well but it is not recommended. One should not really depend on an object's key insertion order.

    function groupAndCollectBySameKeyValue({ key, result }, item) {
      const groupValue = item[key];
      (result[groupValue] ??= []).push(item);
      return { key, result };
    }
    
    var dataArr = [
      { permalink: 'link', subreddit: 'laravel' },
      { permalink: 'link', subreddit: 'mac' },
      { permalink: 'link', subreddit: 'ArtisanVideos' },
      { permalink: 'link', subreddit: 'laravel' },
      { permalink: 'link', subreddit: 'ArtisanVideos' },
      { permalink: 'link', subreddit: 'chrome' },
      { permalink: 'link', subreddit: 'ArtisanVideos' },
      { permalink: 'link', subreddit: 'laravel' },
    ];
    console.log(
      dataArr
        .reduce(groupAndCollectBySameKeyValue, {
          key: 'subreddit',
          result: {},
        })
        .result
    );
    console.log(
      Object
        .entries(
          dataArr
            .reduce(groupAndCollectBySameKeyValue, {
              key: 'subreddit',
              result: {},
            })
            .result
        )
        .sort(([aKey, aValue], [bKey, bValue]) =>
          // array length first, or locale property name comparison.
          bValue.length - aValue.length || aKey.localeCompare(bKey)
        )
        .reduce((result, [key, value]) =>
          // create object by aggregating entries while following
          // the above sorted key precedence / key insertion order.
          Object.assign(result, { [key]: value }), {}
        )
    );
    .as-console-wrapper { min-height: 100%!important; top: 0; }