reduce to group

PHOTO EMBED

Mon Mar 07 2022 15:00:17 GMT+0000 (Coordinated Universal Time)

Saved by @dvinci #javascript

var arr = [
  {
    id: 1,
    name: 'sadf'
  },
  {
    id: 2,
    name: 'cvb'
  },
  {
    id: 3,
    name: 'kl'
  }
]

const obj = arr.reduce( (prev,next) => {
  // grab the id from item
  const { id } = next
  
  // add the item to our object
  prev[id] = next
  
  // return the object so we can add more items
  return prev
}, {});

obj

var gg = arr.reduce( (prev, next) => {
  // grab the property from the item that we want to group by
  const {name} = next;
  
  // add a new array to the object if this is the first one with this value
  if (prev[name] === undefined) {
    prev[name] = [];
  }
  
  prev[name].push(next);
  
  return prev;
}, {})

gg
content_copyCOPY

group