In a reduceRight (or reduce), there is 2 arguments
- A callback
- The initial value (optional, in that case
last/first will be init value, and it will start from second-last/second for reduceRight/reduce accordingly)
Now the callback having 4 arguments,
- The accumulator (what we returned (each) last time, init or last/first value for the first time)
- Each entry (from second last/second depending on init value passed or not)
- Current index
- The Entire Collection (This is mostly useful when you are in a continuous chain)
All you have to do is, (assuming you have to add last N number)
IF (Collection length - Current index) <= N Then Add Current Value with sum and return
ELSE Return Current Sum ignoring current value
So you can do,
array.reduceRight((sum, each, idx, a) => (a.length - idx) > N ? sum : sum + each , 0)
Now, you can remove the ternary and do (sum + either 0 or Each Number) conditionally
so sum + ((array.length - idx) <= N && each)
If the condition (array.length - idx) <= N is false it will return false and it will not go to the and operator otherwise it will return value of each, so it will add false (0) or each value conditionally
array.reduceRight((sum, each, idx, a) => sum + ((a.length - idx) <= N && each), 0)
let arr = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000],
N = 4,
sum = arr.reduceRight((s, e, i, a) => s + ((a.length - i) <= N && e), 0);
console.log(`Sum of last ${N} values: :`, sum);