Tengo dos matrices. Uno con tipos de ropa y otro con colores. Ambos son siempre iguales en longitud. Y coinciden en longitud y posición. Así que la camiseta de la primera prenda, es en rojo y en naranja. Me gusta:
const clothing = ['shirt', 'jacket', 'jeans', 'jeans', 'shirt', 'jeans', 'shirt', 'jacket']; const colors = ['red, orange', 'blue, red', 'red, orange, blue', 'red, blue', 'orange', 'blue', 'red, blue', 'orange, blue'];La longitud de la matriz puede ser diferente y puede haber más tipos de ropa. Los colores son siempre rojo, naranja o azul.
¿Qué tipo de fórmula necesito para obtener la cantidad total de colores para cada tipo de ropa?
El resultado que me gustaría es
outcome = [{ shirt: [number of shirts in red, number of shirts in orange, number of shirts in blue]; jacket: [number of jackets in red, number of jackets in orange, number of jackets in blue]; jeans: [number of jeans in red, number of jeans in orange, number of jeans in blue]; }]Puede usar un 'agrupar por' anidado en la prenda y el color según el índice. Aquí usando bucles for...of anidados, el externo en las entries() de la matriz de ropa y el interno en la cadena de color analizada por índice en la matriz de colores.
Dejé el resultado como un objeto, pero simplemente puede mapear sus valores para formar las matrices en su salida esperada.
const clothing = ['shirt', 'jacket', 'jeans', 'jeans', 'shirt', 'jeans', 'shirt', 'jacket']; const colors = ['red, orange', 'blue, red', 'red, orange, blue', 'red, blue', 'orange', 'blue', 'red, blue', 'orange, blue']; const totals = {}; for (const [i, item] of clothing.entries()) { const itemColors = colors[i].split(',').map(c => c.trim()); totals[item] ??= {}; for (const c of itemColors) { totals[item][c] = (totals[item][c] ?? 0) + 1; } } console.log('number of shirts in red:', totals.shirt.red); console.log('Totals:', totals); // You can simply map the totals object as you see fit, here to your expecte 'outcome' const outcome = [Object.fromEntries( Object.entries(totals) .map(([k, { red = 0, orange = 0, blue = 0 }]) => [k, [red, orange, blue]]) )]; console.log('Outcome:', outcome)A continuación puede haber una posible solución para lograr el objetivo deseado.
Fragmento de código
const countItems = (ar1, ar2) => ( [ ar1.reduce( (fin, itm, idx) => ({ ...fin, [itm]: [ (fin[itm]?.[0] || 0) + (ar2[idx].includes('red') ? 1 : 0), (fin[itm]?.[1] || 0) + (ar2[idx].includes('orange') ? 1 : 0), (fin[itm]?.[2] || 0) + (ar2[idx].includes('blue') ? 1 : 0) ] }), {} ) ] ); const clothing = ['shirt', 'jacket', 'jeans', 'jeans', 'shirt', 'jeans', 'shirt', 'jacket']; const colors = ['red, orange', 'blue, red', 'red, orange, blue', 'red, blue', 'orange', 'blue', 'red, blue', 'orange, blue']; console.log(countItems(clothing, colors));Explicación
.reduce para iterar sobre la matriz de ropafin del agregador se inicializa en un objeto vacíofin , incremente los contadores red , orange y blue en consecuenciafinRecomendaría esta solución. A diferencia de la respuesta que aceptó, esto no tiene valores codificados, por lo que admitirá cualquier cantidad de nombres de productos y cualquier cantidad de colores.
const clothing = ['shirt', 'jacket', 'jeans', 'jeans', 'shirt', 'jeans', 'shirt', 'jacket']; const colors = ['red, orange', 'blue, red', 'red, orange, blue', 'red, blue', 'orange', 'blue', 'red, blue', 'orange, blue']; const getOutcome = (clothing, colors) => { const map = {}; for (const [i, item] of Object.entries(clothing)) { // Grab our list of colors for this specific clothing item const colorList = colors[i].split(', '); // If this clothing item's array doesn't exist in our map, add it if (!map[item]) map[item] = {}; // Loop through our color list colorList.forEach((color) => { // If that color doesn't yet exist for the item, add it if (!map[item][color]) { map[item][color] = 1; return; } // If it does exist, add 1 to it map[item][color] = map[item][color] + 1; }); } return map; }; console.log(getOutcome(clothing, colors));