-1

Try to get average of values. I have json data going inside that, grabbing the array and using the average function on it. But error returns...

TypeError: arr.reduce is not a function

It's from first console.log(myArray) as per screenshot below. and second console.log with avg function, not working...

data() {
    return {
        myArray:[],
    }
},    
methods: {
    avgArray: function(){
        const sum = arr => arr.reduce((a,c) => (a + c));
        const avg = arr => sum(arr) / arr.length;
        this.estates.forEach((a, index) => {
            this.myArray = a.m2_price;
            console.log(this.myArray);
        });

        console.log(avg(this.myArray));
    }
}

2 Answers2

0
avgArray: function(){
    const sum = arr => arr.reduce((a,c) => (a += c),0); // add equals and init with 0
    const avg = arr => sum(arr) / arr.length;
    this.myArray = this.estates.map(a =>  a.m2_price)
    console.log(avg(this.myArray));
}

You were setting this.myArray as a value and not an array. You could've either pushed the m2_price or map it like above

Reduce function only exists on arrays. Clearly you were logging this.myArray and getting integers. Hence the error.

Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25
-1

That is what reduce is for

const average = array => (array && array.length) ? (array.reduce((sum, item) => sum + item, 0) / array.length) : undefined;


console.log(average([1,2,3,4,5,6]));

export the average function from a file called average.js

Applied to your situation

import { average } from 'pathToYourIncludeLibrary/average';

data() {
    return {
        myArray:[],
    }
},    
methods: {
    avgArray: () => average(this.myArray)
}
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
  • thank you for the answer but I can't apply your code to mine... could you revise it? –  Feb 04 '19 at 07:47
  • Export that average function from a file called average.js "export const average = ..." ... being the rest of the function and then import it into your component – Adrian Brand Feb 04 '19 at 07:52
  • The function is called average but you need to read the average property of the returned value to get it :/ – Oli Crt Feb 04 '19 at 10:39
  • It is just an internal variable on the accumulator, it is still part of the function. – Adrian Brand Feb 04 '19 at 21:56
  • Edited it to get rid of the compound accumulator, no need to calculate the average on each iteration. – Adrian Brand Feb 04 '19 at 23:08