I have a function that store the values of a row in an array onkeyup event. However, there are instances that it would store the same row values but differ on quantity and total but the same id. How would I store it in the array in a way that it would just save the most current set of values of an specific id? I know it's a bit confusing, but please take a look in the image below. Thank you for the help.
I would like to save the ff:
{id:"1", qty:"4", price:"45", total:"180"}
{id:"2", qty:"3", price:"10", total:"30"}
{id:"3", qty:"50", price:"12", total:"600"}
{id:"4", qty:"60", price:"12", total:"720"}
My Code:
var arrayVar = [];
var data;
$(function(){
$('#tbl-po-list').on( 'keyup change' , 'input[type="number"]' ,function(){
$(this).parents('.info').find('.total').val($(this).val() * $(this).parents('.info').find('.price').val());
data = {
id: $(this).parents('.info').find('.prod-id').val(),
qty: $(this).val(),
price: $(this).parents('.info').find('.price').val(),
total: $(this).parents('.info').find('.total').val()
}
arrayVar.push(data);
for(var i = 0; i < arrayVar.length; i++){
console.log(arrayVar[i]);
}
});
});
You can achieve that if you replace:
arrayVar.push(data);
by:
for(var i = 0; i < arrayVar.length; i++){
if (arrayVar[i].id === data.id) break; // found the same id!
}
arrayVar[i] = data;
If the loop does not find the same id, then after the loop i will equal arrayVar.length, and so the assignment will be like a push.
If on the other hand the id is found, then the loop exits, and the assignment will replace whatever was in that array element before.
A more concise version of the same:
for(var i = 0; i < arrayVar.length && arrayVar[i].id !== data.id; i++);
arrayVar[i] = data;
Seems ripe for some code golf. Here's my attempt:
o=data.reduce((a,v)=>a[v.id]=v&&a,{});Object.keys(o).map(k=>o[k]);
Original code:
obj = data.reduce((accum, value, i) => {
accum[value.id] = value;
return accum;
})
out = Object.keys(obj).map(key => obj[key]);
This works by using reduce to accumulate values into an object - using the id as the key means rows with the same ID will get overwritten - and then extracts the values from the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With