Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
¿Cómo hago matemáticas con dos matrices diferentes?

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]; }]
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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)

about 4 years ago · Juan Pablo Isaza Denunciar

0

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

  • Use .reduce para iterar sobre la matriz de ropa
  • La fin del agregador se inicializa en un objeto vacío
  • Si la iteración actual está presente en fin , incremente los contadores red , orange y blue en consecuencia
  • De lo contrario, agregue la iteración actual para fin
about 4 years ago · Juan Pablo Isaza Denunciar

0

Recomendarí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));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda