JS实现groupby功能

JS实现groupby功能

const products = [
  { name: 'apples', category: 'fruits' },
  { name: 'oranges', category: 'fruits' },
  { name: 'potatoes', category: 'vegetables' }
];

function groupBy( array , f ) {
  let groups = {};
  array.forEach( function( o ) {
      let group = JSON.stringify( f(o) ); // ["fruits"]
      groups[group] = groups[group] || [];
      groups[group].push( o );
  } );
  return Object.keys(groups).map( function( group ) {
      return groups[group];
  });
}
let rs = groupBy(products, function(item){
  return [item.category];
});

console.log(groupBy(products, function(item) {
  return [item.category]
}))

你可能感兴趣的:(javascript,开发语言,ecmascript)