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

Time:05-18

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

CodePudding user response:

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

CodePudding user response:

Ok. Here you have it.

First, we sort the data:

    let sorted = data.sort((a, b) => (a.subreddit > b.subreddit) ? 1 : -1);
    console.log("sorted: ", sorted);

Please notice that we only sort by the property subreddit just to group them together for the next step.

Next, we create a new object, by creating a new array if the property is undefined:

  let output = {};
    data.forEach((elem) => {
      if(output[elem.subreddit] === undefined){
        output[elem.subreddit] = new Array();
      }
      output[elem.subreddit].push(elem);
    });

Finally, we do a test to make sure everything is as we expected:

console.log("same? :", JSON.stringify(expected) == JSON.stringify(output));

let data = [
  { "permalink" : "https://www.apple.com", "subreddit": "mac" }, 
  { "permalink" : "https://www.microsoft.com", "subreddit": "microsoft" }, 
  { "permalink" : "https://www.xcode.com", "subreddit": "mac" }, 
  { "permalink" : "https://www.xbox.com", "subreddit": "microsoft" }, 
];

let expected = {
  "mac": [
    { "permalink" : "https://www.apple.com", "subreddit": "mac" }, 
    { "permalink" : "https://www.xcode.com", "subreddit": "mac" }
  ],
  "microsoft": [
    { "permalink" : "https://www.microsoft.com", "subreddit": "microsoft" }, 
    { "permalink" : "https://www.xbox.com", "subreddit": "microsoft" }, 
  ]
};


let sorted = data.sort((a, b) => (a.subreddit > b.subreddit) ? 1 : -1);
console.log("sorted: ", sorted);

let output = {};
data.forEach((elem) => {
  if(output[elem.subreddit] === undefined){
    output[elem.subreddit] = new Array();
  }
  output[elem.subreddit].push(elem);
});

console.log("output: ", output);
console.log("same? :", JSON.stringify(expected) == JSON.stringify(output));

Enjoy.

  • Related