ive been better understanding reduce un-nesting arrays turning arrays into objects getting a feel for how it operates however i found a cool artical on freecodecamp and am going though the examples and one seems to acting strangly
let arr = [2,4,6,8]
const newArr = arr.reduce((total, amount, index, array) => {
total += amount
return total/array.length
}, 0); // comes to 2.4453125
it comes to a werird number instead of 5 why is this? the strange thing is ive been going though the functional programming part of the course again and yesturday a calucated an avg using reduce without an issue. i console.loged array.length and it is 4 and if i take it off the total comes to 20 so i have no idea why its behaving like this for me i also tried another online editor just to check.
Now, first iteration: total is 0, amount is 2. The callback returns 2/4, and this is the total for next iteration
Now total is 0.5 and amount is 4, the callback returns 4.5/4. This is the total for next iteration.
Etc
If you want to have the division inside the reduce method, be sure to not divide total by it as it was already divided in previous iteration
thankks for all the help! i think today was a bad try 2 try and study havnt been sleeping well lol but i got it 2 work using this
let arr = [2,4,6,8]
const newArr = arr.reduce((total, amount, index, array) => {
total += amount;
if( index === array.length-1) {
return total/array.length;
}else {
return total;
}
});
console.log(newArr)
i thought return ended a function so using it twice confused me im really bad at this lol is it that return is returning it to the accumulator untill the its went over the whole array and then the final return, returns it to the average variable or am i still getting confused on how this works? sorry for the all the questions.
i did cs50 on edex last year before i had an trumatic event which ment i cudnt study for about a year and remember things like big O notation. ill look up associative propertys if theres any other bits of maths which would help write more efficient algorithms I would be intrested in looking at it if its not 2 insanely taxing. (i think thats what your getting at the method above would have a better runtime?)
im enjoying learning this again but its very hard and some days it feels alot harder than others lol im really thankful for your feedback! tomorow ill be going over more uses of reduce to get a better understanding of how it works im getting there i think.