Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda