I'm trying to solve a task. I know is quite basic as i'm just starting and studying for tech interview for a bootcamp. I'd be really grateful if someone could help me understand some whys. The following code should work adding my own method. It's a beginner excercise for getting an average. I could have done it with a for loop maybe, but i was trying to implement the reduce method.
This is the given code
var arr = [1, 2, 3, 4, 5];
var avg = arr.average();
console.log(avg);
I've been able to get the average with the following code.
var arr = [1, 2, 3, 4, 5];
function average() {
const accPlusCur =(acc,cur) => acc + cur;
const sumOfAll = arr.reduce(accPlusCur);
return sumOfAll / arr.length;
};
console.log(average());
// => 3
The problem is i'm not really using exactly the given code. So i re wrote it this other way to try to have a function that i could apply to any array and not just this specific one. But it is not working.
var arr = [1, 2, 3, 4, 5];
function average(arrayName) {
const accPlusCur = (acc,cur) {return acc + cur}, 0;
const sumOfAll = arrayName.reduce(accPlusCur);
return sumOfAll / arrayName.length;
};
const avg = average();
console.log(avg);
The solution given online is the following. Although i don't really quite get it.
Array.prototype.average = function() {
var sum = this.reduce(function(prev, cur) { return prev + cur; });
return sum / this.length;
}
var arr = [1, 2, 3, 4, 5];
var avg = arr.average();
console.log(avg); // => 3
Could someone please help me? Why is my second try not working as my first option did. What's the thing with this prototype method and the constatnt use of "this". Whi is Array word before prototype?