-2

Lets say I have values I have assigned in array in objects. I want to use reduce() to add them up. The workflow will work like this: x-data=" {package_type: [], online_implant_meeting: [], total() { return "do the math here" }} then inside x-text="total()"

I am using alpine.js to bind stuff. How do I do the calculation inside the function?

 <div class="addingPrices" x-data="{package_type: [20], online_implant_meeting: [250],  total(package_type, online_implant_meeting){ 
return package_type + online_implant_meeting;
     }} >
</div>
adiga
  • 34,372
  • 9
  • 61
  • 83
Francis
  • 115
  • 2
  • 12
  • I've not worked with alpine.js before. can you access `package_type` and `online_implant_meeting` inside the function this way (let say if you were to `console.log` them)? – Tibebes. M Sep 12 '20 at 16:21
  • I can access them when I console total(item, item). The problem is I get values append to each other. 20250 – Francis Sep 12 '20 at 16:24

1 Answers1

1

Here is one approach to do it via the spread operator (to merge the 2 arrays) and then sum them up with reduce:

<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.js"></script>
<div class="addingPrices" x-data="{
    package_type: [89],
    online_implant_meeting: ['150'],

    total(package_type, online_implant_meeting) {
       return [...package_type, ...online_implant_meeting].map(Number).reduce((acc, curr) => acc + curr, 0)
    }
}">
  <span x-text.number="total(online_implant_meeting, package_type )"></span>

</div>
Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
  • ```
    ``` `````` . Now I get get value as 015089.00 let say the values are 89, 150
    – Francis Sep 12 '20 at 16:53
  • inside your ``, just do `x-text.number="total(online_implant_meeting, package_type )"` (without the squared brackets) - these variables already reference array values, I added the braces in my example because I was testing it via numeric literals – Tibebes. M Sep 12 '20 at 17:09
  • It returns the same values 015089.00 – Francis Sep 12 '20 at 17:13
  • you must be doing something else wrong. [check out this codepen](https://codepen.io/tibebes/pen/zYqjMdM?editors=1111) – Tibebes. M Sep 12 '20 at 17:21
  • Please, check code pen I have created https://codepen.io/apetwebc/pen/RwaMWNa – Francis Sep 12 '20 at 17:21
  • Oh, you are mixing `string`s there.. that's what causing the issue – Tibebes. M Sep 12 '20 at 17:32
  • 1
    just add `.map(Number)` to fix it.. like this: `return [...online_implant_meeting, ...package_type].map(Number).reduce((acc, curr)=> acc + curr, 0); ` – Tibebes. M Sep 12 '20 at 17:33
  • 1
    I owe you. Thank you very much. I am new to declarative javascript. – Francis Sep 12 '20 at 17:37