Home > Software engineering >  Find the duplicates in array and add the value of that indexes of another array
Find the duplicates in array and add the value of that indexes of another array

Time:12-31

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
var product_id =$("form[name='id[]']").map(function(){return $(this).value();}).get()

var product_category_id =$("form[name='cat_id[]']").map(function(){return $(this).value();}).get()

var product_amount =$("form[name='amount[]']").map(function(){return $(this).value();}).get()

for(var i=0;i<product_id.length;i  ){
if(product_id[i] = product_id[i 1]
{
product_new_amount[i]  = product_amount;
}}

the above i was trying to do but have no idea how to get all together.

CodePudding user response:

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

  • Related