Javascript Array groupBy(fn)

Description

Javascript Array groupBy(fn)


Array.prototype.groupBy = function (fn) {
  var result = {//from   w w  w . j  a va2 s. c o m
  };
  for (var i = 0; i < this.length; i++)
  {
    try {
      if (!result[fn(this[i])])
      {
        result[fn(this[i])] = [
        ];
      }
      result[fn(this[i])].push(this[i]);
    } 
    catch (e) {
      if (!result[this[i]])
      {
        result[this[i]] = [
        ];
      }
      result[this[i]].push(this[i]);
    }
  }
  return result;
}

Javascript Array groupBy(fn)

Array.prototype.groupBy = function(fn){
  fn = fn || function(x){ return x; };

  return this.reduce(function(obj, val){
    var key = fn(val);
    obj[key] ? obj[key].push(val) : obj[key] = [val];
    return obj;//from  w  w  w. j  a v  a  2 s. com
  }, {});
};

// -------------------------------------------- //

var x = [1,2,3,2,4,1,5,1,6].groupBy();
console.log(x);
var y = [1,2,3,2,4,1,5,1,6].groupBy(function(val) { return val % 3;} )
console.log(y);

Javascript Array groupBy(fn)

// [1,2,3,2,4,1,5,1,6].groupBy()
// {//from   w  w w  . jav a  2 s . co m
//   1: [1, 1, 1],
//   2: [2, 2],
//   3: [3],
//   4: [4],
//   5: [5],
//   6: [6]
// }

// [1,2,3,2,4,1,5,1,6].groupBy(function(val) { return val % 3;} )
// {
//   0: [3, 6],
//   1: [1, 4, 1, 1],
//   2: [2, 2, 5]
// }

Array.prototype.groupBy = function(fn) {
  if (fn == null) fn = function(x) { return x }
  return this.reduce(function(groups, val) {
    var key = fn(val)
    groups[key] ? groups[key].push(val) : groups[key] = [val]
    return groups
  }, {})
}

Javascript Array groupBy(fn)

Array.prototype.groupBy = function(fn) {
 var origninal = this,
  result = {};/* w  w  w .  jav  a  2  s .c o m*/

 if (typeof fn === 'undefined') {
  this.forEach(function(v, i, a) {
   result[v] = a.filter(function(e) {
    return e === v;
   });
  });
 } else {
  this.map(fn).forEach(function(v, i, a) {
   var temp = [];

   a.filter(function(e, n) {
    if (e === v) {
     temp.push(origninal[n]);
    }
     return e === v;
   });

   result[v] = temp;
  });
 }

 return result;
};

// Array.prototype.groupBy = function(fn) {
//   return this.reduce(function(o, a){
//     var v = fn ? fn(a) : a;
//     return (o[v] = o[v] || []).push(a), o;
//   }, {});
// };

[1,2,3,2,4,1,5,1,6].groupBy();
[1,2,3,2,4,1,5,1,6].groupBy(function(val) { return val % 3; });
['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'].groupBy(function(_) {return _.length;});



PreviousNext

Related