Increment values in objects

Asked

Viewed 220 times

2

let items = [
  { prod: '', qty: 50, vUnit: 5 },
  { prod: '', qty: 10, vUnit: 20 },
  { prod: '', qty: 5, vUnit: 10 },
];
let mail = [
  { name: 'Joãozinho', email: '[email protected]', value: null },
  { name: 'Mariazinha', email: '[email protected]', value: null },
  { name: 'Lindomar', email: '[email protected]', value: null },
];
let addQty = () => {
  let total = items.reduce(function getTotal(total, item) {
    return total + item.qty * item.vUnit;
  }, 0);
  return total;
};
let mailDelivery = () => {
  mail.forEach(({ email, value }) => {
    console.log(
      email +
        ' deve pagar ' +
        Intl.NumberFormat('pt-br', {
          style: 'currency',
          currency: 'BRL',
        }).format(value / 100),
    );
  });
};
function sharedValue() {
  clients = mail.length;
  let total = addQty();
  let shared = total / clients;
  mail.map((x) => {
    x.value = parseInt(shared);
  });
  if (total === parseInt(shared) * clients) {
    return mailDelivery();
  } else {
    diff = total - parseInt(shared) * clients;
    //Aqui não faço ideia de como continuar

    return mailDelivery();
  }
}
sharedValue();

I have both objects and I have the following situations:

  • calculate the sum of the values, that is, multiply the price of each item by its quantity and sum all the items
  • Divide the value equally between the number of emails

Only the next point comes in:

  • When you make the division, it is important that no penny is missing! For example, a total amount of R $ 1,00 to be divided between 3 emails. This would give an infinite tithe. However, the correct thing here is for two people to be 0.33 and the third to be 0.34.

My idea was to return the difference between the total value and the sum of the values divided between clients, however, I have no idea how I could be increasing this value in "mail.value" and subtracting from the difference obtained...

  • 1

    I don’t know if this answers your question but can add the difference, for example, to the last: mail[mail.length - 1].value += diff;.

  • I thought of something like that too, my brother, only like, when he goes to that point of "However, the correct thing here is that two people get the value 0.33 and the third gets 0.34." in the code that I built the diff would be equal to 2, in this I would have to equally divide these 2 being 1 for the Indice 0 and 1 for the Indice 1 of the array

  • See my answer below.

1 answer

1


You can make a small loop and distribute the diff value. Anything like:

for (var i = 1; i <= diff; i++) {
  mail[mail.length - i].value ++;
}
  • MANO DO CÉU, saved beautifully, I kept thinking of a thousand ways but it was only going in the basic same kkkkkkkkkk

Browser other questions tagged

You are not signed in. Login or sign up in order to post.