[Vuejs]-How do I average two arrays with same elements?

0👍

You can create a method that accepts index, and returns average value. To get value just use Object.keys[0], to convert to Number use unary + operator.

methods: {
  getAvarageByIndex(index) {
    return (+Object.values(this.array1[index])[0] + +Object.values(this.array2[index])[0]) / 2;
  }
}
new Vue({
  el: "#app",
  data: {
    array1: [{
        pizza: "20"
      },
      {
        popcorn: "7"
      },
      {
        pretzel: "15"
      },
      {
        fries: "11"
      }
    ],
    array2: [{
        pizza: "9"
      },
      {
        popcorn: "17"
      },
      {
        pretzel: "5"
      },
      {
        fries: "4"
      }
    ]
  },
  methods: {
    getAvarageByIndex(index) {
      return (+Object.values(this.array1[index])[0] + +Object.values(this.array2[index])[0]) / 2;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>
    <span>{{ getAvarageByIndex(2) }}</span>
  </div>
</div>

Leave a comment