Javascript Array groupBy(callback)

Description

Javascript Array groupBy(callback)


Array.prototype.groupBy = function(callback) {
    let obj = {}/*from  w  ww .ja  v a 2 s  .c  o  m*/
    this.forEach(el => {
        let index = callback(el)
        if (!obj.hasOwnProperty(index)) {
            obj[index] = []
        }
        obj[index].push(el)
    })
    return obj
}

Javascript Array groupBy(callback)

Array.prototype.groupBy = function(callback){
var results = {};
  this.forEach(function (el){
    var key = callback(el);
    if (key in results === false) {
      results[key] = [];//from  w w w.j  av a 2s  .  c o  m
    }
    results[key].push(el);
 });
  return Object.keys(results).map(function(key) {
    return {
      key: key,
      values: results[key]
    };
  });
};

var grouped = [1,2,3,4,5,6,7,8,9,10].groupBy(function(v, i, arr){
  return (v % 2 === 0) ? 'even' : 'odd';
});

console.log(grouped);



PreviousNext

Related