Quiero devolver una nueva matriz usando reducir. Por ejemplo,
const product = [ { color: 'orange', type: 'hat', count: 1 }, { color: 'orange', type: 'hat', count: 1 }, { color: 'orange', type: 'shoes', count: 1 }, { color: 'blue', type: 'food', count: 1 }, ];la lista de productos debe gustar a continuación porque hay dos 'sombrero', por lo tanto, el recuento debe ser 2 y uno { color: 'naranja', tipo: 'sombrero', recuento: 1 } debe eliminarse.
const result = product.reduce((acc, curr) => { // I want to make new array like // const product = [ // { color: 'orange', type: 'hat', count: 2 }, // { color: 'orange', type: 'shoes', count: 1 }, // { color: 'blue', type: 'food', count: 1 }, //]; return acc }¡gracias!
Yo lo haría de la siguiente manera:
currcountNota : he usado el operador Spread para hacer una copia profunda del objeto en lugar de insertar el objeto actual en la matriz.
Este resultado al no modificar la matriz de products y crear una matriz completamente nueva
const product = [ { color: 'orange', type: 'hat', count: 1 }, { color: 'orange', type: 'hat', count: 1 }, { color: 'orange', type: 'shoes', count: 1 }, { color: 'blue', type: 'food', count: 1 }, ]; const result = product.reduce((acc, curr) => { if(!acc) return [...curr] const exist = acc.find(x => x.type === curr.type && x.color === curr.color) exist ? exist.count += 1 : acc.push({...curr}) return acc }, []) console.log(result)Puedes probarlo
const product = [ { color: 'orange', type: 'hat', count: 1 }, { color: 'orange', type: 'hat', count: 1 }, { color: 'orange', type: 'shoes', count: 1 }, { color: 'blue', type: 'food', count: 1 }, ]; const result = product.reduce((res, obj) => { let exist = res.find(o => o.color === obj.color && o.type === obj.type) if (exist) { exist.count += obj.count } else { res = [...res, {...obj}] } return [...res] }, []) console.log(result) console.log(product)Actualizar Editar con sugerencia de yassine-el-bouchaibi
Del comentario anterior...
La tarea también podría describirse como agrupar, fusionar y agregar . Es una tarea bastante común y puede resolverse mediante una función reductora implementada de forma genérica pero personalizable... consulte... "¿Cómo agrupar y fusionar entradas de matrices y resumir valores en varias claves comunes (pero no todas)?"
... demostrar ...
function groupMergeAndAggregateGenerically(collector, item) { const { createKey, createMerger, aggregate, lookup, result = [], } = collector; const key = createKey(item); let merger = lookup.get(key) ?? null; if (merger === null) { merger = createMerger(item); lookup.set(key, merger); result.push(merger); } aggregate(merger, item); return collector; } const productData = [ { color: 'orange', type: 'hat', count: 1 }, { color: 'orange', type: 'hat', count: 1 }, { color: 'orange', type: 'shoes', count: 1 }, { color: 'blue', type: 'food', count: 1 }, ]; const { result: mergedData } = productData .reduce(groupMergeAndAggregateGenerically, { createKey: ({ color, type }) => [color, type].join('_'), createMerger: ({ color, type }) => ({ color, type, count: 0 }), aggregate: (merger, { count }) => merger.count += count, lookup: new Map, result: [], }); console.log({ mergedData, productData }); .as-console-wrapper { min-height: 100%!important; top: 0; }