¿Cómo puedo usar .reduce() para agrupar por el valor? Entonces, si tengo lo siguiente:
const arr = [ { id: 1, value: 'abc', othervalue: '123' }, { id: 2, value: 'def', othervalue: '123' }, { id: 3, value: 'def', othervalue: '123' }, { id: 4, value: 'ghi', othervalue: '123' } ]Quiero esto :
{ 'abc' : [{id:1, value:'abc', othervalue: '123'}] 'def' : [{id:2, value:'def', othervalue: '123'}, {id:3, value:'def', othervalue:'123'}], 'ghi' : [{id:4, value:'ghi', othervalue: '123'}] }Intenté esto pero no funcionó:
arr.reduce( (acc,p) => ({...acc, [p.value]:p }))
No es un trazador de líneas pequeño, pero es legible
const arr = [{ id: 1, value: 'abc', othervalue: '123' }, { id: 2, value: 'def', othervalue: '123' }, { id: 3, value: 'def', othervalue: '123' }, { id: 4, value: 'ghi', othervalue: '123' } ] let grouped = arr.reduce((b, a) => { b[a.value] = b[a.value] || []; b[a.value].push(a); return b }, {}) console.log(grouped)Lo que tienes está cerca, pero asegúrate de:
acc correctamente(acc[p.value]||[]).concat(p){} como el segundo argumento arr.reduce((acc,p) => ({ ...acc, [p.value]: (acc[p.value]||[]).concat(p) }), {})