Advertisement
rgruber

Javascript groupBy function

Dec 25th, 2022 (edited)
951
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function groupBy(array, key) {
  2.   return array.reduce(function(result, currentValue) {
  3.     (result[currentValue[key]] = result[currentValue[key]] || []).push(currentValue);
  4.     return result;
  5.   }, {});
  6. }
  7.  
  8.  
  9. // counter
  10. function groupBy(array, key) {
  11.   return array.reduce(function(result, currentValue) {
  12.     var group = currentValue[key];
  13.     if (!result[group]) {
  14.       result[group] = { count: 0, values: [] };
  15.     }
  16.     result[group].count++;
  17.     result[group].values.push(currentValue);
  18.     return result;
  19.   }, {});
  20. }
  21.  
  22.  
  23. // inet_ntoa
  24. function numberToIp(number) {
  25.   var parts = [];
  26.   for (var i = 3; i >= 0; i--) {
  27.     parts[i] = number & 255;
  28.     number = number >> 8;
  29.   }
  30.   return parts.join('.');
  31. }
  32.  
Tags: groupby
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement