Home > Enterprise >  How to sum certain index in an array in javascript
How to sum certain index in an array in javascript

Time:09-22

Let's say I have an array.

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

Breakdown for a single item in the array goes by 219_1_undefined basically is 219 is product_id, 1 is the quantity and undefined is the product_options I'm storing these information in local storage. Now I have a new item that needs to be added to the cart, but this product is already in cart so I want to add the quantity alone (middle value). So I want to add 219_1_undefined again to the existing array. Now the array will be look like this.

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

My problem is I don't know how to add the middle value(quantity) of the same product and get result like

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

Below is the code I tried

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 matter what I do I still get the wrong output.

CodePudding user response:

You can try getting the index using Array.prototype.findIndex() and update the array item using that index:

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

CodePudding user response:

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('|');

I tested this and it appears to work.The if statement compares botht he ID and param, but obviously you can only have it check the ID if you want.

  • Related