How to get the last value of a specific identifier in an array using javascript?

I have a function that stores string values ​​in the onkeyup event of an array. However, there are instances in which they will store the same string values, but they differ in quantity and amount, but in the same identifier. How to save it in an array so that it just stores the most recent set of values ​​of a specific identifier? I know this is a bit confusing, but please take a look at the image below. Thank you for your help.

enter image description here

I would like to keep 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 is:

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

    });   

  });
+4
source share
4 answers

This can be done 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;

, arrayVar.length, push.

, , , , , .

:

for(var i = 0; i < arrayVar.length && arrayVar[i].id !== data.id; i++);
arrayVar[i] = data;
+2

, . :

o=data.reduce((a,v)=>a[v.id]=v&&a,{});Object.keys(o).map(k=>o[k]);

:

obj = data.reduce((accum, value, i) => {
  accum[value.id] = value;
  return accum;
})
out = Object.keys(obj).map(key => obj[key]);

reduce - , , - .

+2

, splice() for, :

var id = $(this).parents('.info').find('.prod-id').val();

for(var i = 0; i < arrayVar.length; i++){
   if(arrayVar[i]['id'] == id){
       arrayVar.splice(i, 1);
   }
}

+1

, ( id) . unshift .

var index = [], out = [];
for (var i = arr.length - 1; i >= 0; i--) {
  if (index.indexOf(arr[i].id) === -1) {
    index.push(arr[i].id);
    out.unshift(arr[i]);
  }
}

DEMO

+1

All Articles