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

229
Vistas
Cómo sumar cierto índice en una matriz en javascript

Digamos que tengo una matriz.

[ '219_1_undefined', '244_1_undefined', '248_1_20///179+25///153', '221_6_undefined' ]

El desglose de un solo elemento en la matriz pasa por 219_1_undefined básicamente es 219 es product_id , 1 es la cantidad y undefined es product_options . Estoy almacenando esta información en el almacenamiento local. Ahora tengo un artículo nuevo que debe agregarse al carrito, pero este producto ya está en el carrito, así que quiero agregar solo la cantidad (valor medio). Entonces quiero agregar 219_1_undefined nuevamente a la matriz existente. Ahora la matriz se verá así.

[ '219_1_undefined', '244_1_undefined', '248_1_20///179+25///153', '221_6_undefined', '219_1_undefined' ]

Mi problema es que no sé cómo agregar el valor medio (cantidad) del mismo producto y obtener resultados como

[ '244_1_undefined', '248_1_20///179+25///153', '221_6_undefined', '219_2_undefined' ]

A continuación se muestra el código que probé

 let pid = 219; let qty = 1; let params = "undefined"; let string = '219_1_undefined|244|1_undefined|248_1_20///179+25///153|221_1_undefined'; let items = string.split('|'); let nItem = pid+'_'+qty+'_'+params; let mx = items; mx = mx.filter(function (item) { return item.indexOf(pid+'_') !== 0; }); mx.push(nItem); var result = mx.toLocaleString(); let nresult = result.split(',').join('|'); console.log(nresult);

No importa lo que haga, sigo obteniendo el resultado incorrecto.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Puede intentar obtener el índice usando Array.prototype.findIndex() y actualizar el elemento de la matriz usando ese índice :

 let pid = 219; let qty = 1; let params = "undefined"; let items = ['219_1_undefined', '244_1_undefined', '248_1_20///179+25///153', '221_1_undefined']; //get the index of the item from the array by matching the id let index = items.findIndex(p => p.split('_')[0] == pid); //check if any item is exist in the array if(index > -1){ //using the index update the item in the array with the new value items[index] = pid + '_' + (+items[index].split('_')[1] + qty) + '_' + params; } else{ //push new item to the arry items.push(pid + '_' + qty + '_' + params); } console.log(items);

about 4 years ago · Juan Pablo Isaza Denunciar

0

let pid = 219; let qty = 1; let params = "undefined"; let string = '219_1_undefined|244|1_undefined|248_1_20///179+25///153|221_1_undefined'; let items = string.split('|'); let i = 0; for(; i < items.length; i++) { let temp = items[i].split('_'); if (temp[0] == pid && temp[2] == params) { qty = parseInt(qty) + parseInt(temp[1]); break; } } items[i] = `${pid}_${qty}_${params}`; string = items.join('|');

Probé esto y parece funcionar. La declaración if compara tanto la ID como el parámetro, pero obviamente solo puede hacer que verifique la ID si lo desea.

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