Necesito agrupar objetos comunes para que sean únicos con conteo, cómo agrupar el objeto según la identificación en el objeto y cómo agregar una clave adicional con conteo en el resultado.
var a =[ {"name":"test","id":101,"price":100}, {"name":"test","id":101,"price":100}, {"name":"test3","id":103,"price":10}, {"name":"test2","id":102,"price":12}, ]salida =
[ {"name":"test","id":101,"price":100,"qty":2}, {"name":"test3","id":103,"price":10,"qty":1}, {"name":"test2","id":102,"price":12,"qty":1}, ]Pruebe lo siguiente (ciertamente no es el más rápido pero funciona;):
let myarray = [ {"name":"test","id":101,"price":100}, {"name":"test","id":101,"price":100}, {"name":"test3","id":103,"price":10}, {"name":"test2","id":102,"price":12}, ]; let groupedArray = myarray.reduce((acc, cur) => { let foundIndex = acc.findIndex(a => a.id == cur.id); if (foundIndex != -1){ acc[foundIndex].qty += 1 } else { cur.qty = 1; acc.push(cur) } return acc; }, []); // groupedArray contains the grouped objectsconst a =[ {"name":"test","id":101,"price":100}, {"name":"test","id":101,"price":100}, {"name":"test3","id":103,"price":10}, {"name":"test2","id":102,"price":12}, ]; const output = a.reduce((acc, nv, i, arr) => { const item = acc.find(e => e.id === nv.id); if(item) return acc; acc.push({ ...nv, count: arr.filter(e => e.id === nv.id)?.length }); return acc; }, []);