-2

I have following array

[
  "1",
  "132",
  "151.79999999999998",
  "1",
  "10",
  "11.5",
  "2",
  "100",
  "121"
]

When it starts with VAT_id, price_without_VAT and price_with_VAT (it is table ID_VAT, price without VAT and price with VAT}. I want to summarize every second and third element by first element, so result should be ["1", "142", "163.29","2", "100","121"], and creating summuriying table. I am not able to solve it. Have I to to use objects?

tghw
  • 25,208
  • 13
  • 70
  • 96
Hyp
  • 7
  • 1

1 Answers1

0

You can indeed use objects to store the results, as nothing guarantee that the ids will be in an ordered and continued range from 0.

You also need to iterate 3 items by 3 items, by using for instance the splice method.

const data = [
  "1",
  "132",
  "151.79999999999998",
  "1",
  "10",
  "11.5",
  "2",
  "100",
  "121"
]

const results = {}
// loop until the initial array is empty
while(data.length != 0) {
    // remove 3 items and assign them
    const [id, wo_vat, w_vat] = data.splice(0, 3);
    // initialize the result structure with an id not met before
    if (results[id] == undefined) {
        results[id] = {
            without_vat: 0,
            with_vat: 0
        }
    }
    // increments the result structure matching the id
    results[id].without_vat += parseFloat(wo_vat)
    results[id].with_vat += parseFloat(w_vat)
}
// output the result
console.log(results)
challet
  • 870
  • 9
  • 21