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

135
Visualizações
Find the duplicates in array and add the value of that indexes of another array

I have three arrays

product_id = [];
product_category_id =[];
product_amount =[];

in this the arrays are dynamic as there coming from user selection.but what i want to do is if the product ids are same i want to add the product amounts and take the total with particular product_id,category_id and total amount.

As a example if

product_id = [4,5,1,3,5];
product_category_id =[2,2,1,3,2];
product_amount =[3000,4000,5000,5000,4000];

and here what i want as the output is

product_id || product_category_id || product_new_amount
4                 2                    3000
5                 2                    8000      
1                 1                    5000
3                 3                    5000
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

There are many ways to accomplish your goal, depending on how you want to use the data. If the arrays are always the same length, essentially what you need to do is create a new array of objects, checking to see if the product_id and product_category_id combination have already been added. If they have, you add the product amount to that entry, and if not, you create a new entry to the data.

Once the data is organized in an array, you can do anything you want with it. I filled a table out with the data as a simple demo.

hopefully this points you in the right direction 👍 if you have any questions about my code, please ask.

const product_id = [4,5,1,3,5];
const product_category_id = [2,2,1,3,2];
const product_amount = [3000,4000,5000,5000,4000];
const productData = [];
//format data
for (let i = 0; i < product_id.length;  i++) {
  const pid = product_id[i];
  const pcid = product_category_id[i];
  const prodAmt = product_amount[i];
  const target = productData.find(data => data.pid == pid && data.pcid == pcid);
  if (target) target.prodAmt += prodAmt;
  else productData.push({pid, pcid, prodAmt});
}
//create rows
const table = document.querySelector("table");
for (const data of productData) {
  const tr = document.createElement("tr");
  const values = Object.values(data);
  for (const value of values) {
    const td = document.createElement("td");
    td.innerText = value;
    tr.appendChild(td);
  }
  table.appendChild(tr);
}
<table>
  <tr>
    <th>product_id</th>
    <th>product_category_id</th>
    <th>product_new_amount</th>
  </tr>
</table>

about 4 years ago · Juan Pablo Isaza Relatório

0

This solution can help you. Please, try this:

const product_id = [4,5,1,3,5];
const product_category_id =[2,2,1,3,2];
const product_amount =[3000,4000,5000,5000,4000];

function find_duplicate_in_array(array){
const count = {}; const category_id = {}; const amount = {};
const result = [];

array.forEach((item,index) => {
    if (count[item]) {
       count[item] +=1;
       amount[item] += product_amount[index];
       return
    }
    count[item] = 1; 
    amount[item] = product_amount[index];
    category_id[item] = product_category_id[index];
});

for(let prop in count){
    result.push({product_id:prop,product_category_id:category_id[prop],product_new_amount:amount[prop]})
}

console.log('result---->', result);
return result;
}
find_duplicate_in_array(product_id);
about 4 years ago · Juan Pablo Isaza Relatório

0

First, make objects out of your arrays.

product_id = [4,5,1,3,5];
product_category_id =[2,2,1,3,2];
product_amount =[3000,4000,5000,5000,4000];

function Item(i,ci,a) {
this.id=i;
this.category_id=ci;
this.amount=a;
}

obj=[];
product_id.forEach((v,k)=>{obj.push(new Item(product_id[k],product_category_id[k],product_amount[k]))});
document.write(JSON.stringify(obj),'<br>');

document.write('<br>');

Then create two Map's, one for the id:amount pairing, and the other for the id:category relation.

Run through the amounts, and if the key already exists, add the new value to it. If not, update both Map's with the new key and respective value.

m=new Map(); m2=new Map();
obj.forEach(o=>{
if (m.has(o.id)) m.set(o.id,m.get(o.id)+o.amount);
else {
m.set(o.id,o.amount);
m2.set(o.id,o.category_id);
}
});

Finally, display the data, taking care to use the correct Map.

m.forEach((v,k)=>document.write(k+', '+m2.get(k)+', '+v,'<br>'));

Put it together:

product_id = [4,5,1,3,5];
product_category_id =[2,2,1,3,2];
product_amount =[3000,4000,5000,5000,4000];

function Item(i,ci,a) {
this.id=i;
this.category_id=ci;
this.amount=a;
}

obj=[];
product_id.forEach((v,k)=>{obj.push(new Item(product_id[k],product_category_id[k],product_amount[k]))});
document.write(JSON.stringify(obj),'<br>');

document.write('<br>');

m=new Map(); m2=new Map();
obj.forEach(o=>{
if (m.has(o.id)) m.set(o.id,m.get(o.id)+o.amount);
else {
m.set(o.id,o.amount);
m2.set(o.id,o.category_id);
}
});

m.forEach((v,k)=>document.write(k+', '+m2.get(k)+', '+v,'<br>'));

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