Javascript reduce accumulator explained -
who can kindly explain accumulator acc construction below in plain english?
return arr1.reduce(function(acc, curr){ var last = acc[acc.length-1]; if(acc.length > 0 && curr[1]===last[1]) { last[0] += curr[0]; } else acc.push(curr); return acc; }, []); } this reduce method can used solve freecodecamp "inventory update" assignment, part of advanced algorithm scripting lessons.
link: https://www.freecodecamp.org/challenges/inventory-update. 1 required update existing items in inventory array (arr1) new items in "new delivery" array.
two test arrays, present inventory curinv , new delivery newinv respectively, follows:
var curinv = [ [21, "bowling ball"], [2, "dirty sock"], [1, "hair pin"], [5, "microphone"] ]; var newinv = [ [2, "hair pin"], [3, "half-eaten apple"], [67, "bowling ball"], [7, "toothpaste"] ]; after finding several excellent articles on javascript reduce method (such this post , great video course on egghead.io), , somehow sensing power harnassing, read method follows:
"reduce inventory array, creating empty array [ ] first (the initial value), applying following callback function:
if inventory array not empty (has length greater zero), , name of handled item (index 0 of curr read "bowling ball" example) identical last item of inventory array being updated, update amount of item in inventory array.
last item defined right above if statement, follows: take present length of accumulated array upto now, subtract 1, , use value index accumulated array. element @ index assigned variable 'last'. on other hand, if inventory empty, add new item entirely, - is: item name , amount. return newly accumulated array."
how using length - 1 of accumulator useful make acc accumulate? (pardon alliteration)
i think understand of how reduce method built, please correct me wherever i'm misreading), except particular use of acc.length-1.
cheers, k.
the actual solution involves concatenating , sorting both arrays , reducing them. in case whenever evaluate new item, if name not equal last accumulator item, means it's new item.
using example, list reducing is:
[ [ 21, 'bowling ball' ], [ 67, 'bowling ball' ], [ 2, 'dirty sock' ], [ 1, 'hair pin' ], [ 2, 'hair pin' ], [ 3, 'half-eaten apple' ], [ 5, 'microphone' ], [ 7, 'toothpaste' ] ] so when encounter second item, last value in accumulator [21, 'boweling ball'] , when compare strings go first condition.
Comments
Post a Comment