admin管理员组

文章数量:1356843

I am able to calculate the sum of last n elements of an array using for loop as below. How can I achieve the same using Arr.reduceRight?

x = [1,2,3,4,5];
y = 0
for(let i=x.length; i>x.length-3; i--) {
  console.log(x[i-1]);
  y +=x[i-1];

}
console.log(y);

Here is the codepen link:

I am able to calculate the sum of last n elements of an array using for loop as below. How can I achieve the same using Arr.reduceRight?

x = [1,2,3,4,5];
y = 0
for(let i=x.length; i>x.length-3; i--) {
  console.log(x[i-1]);
  y +=x[i-1];

}
console.log(y);

Here is the codepen link: https://codepen.io/anon/pen/rrNxZB?editors=0011

Share Improve this question asked Aug 29, 2018 at 10:19 Chidu MurthyChidu Murthy 6883 gold badges11 silver badges26 bronze badges
Add a ment  | 

9 Answers 9

Reset to default 3

You can first slice the array, then reduce the resulting array. No need for reduceRight as the sum operation is mutative.

x = [1, 2, 3, 4, 5];

n = 4;

y = x.slice(-n).reduce((acc, val) => acc + val);

console.log(y);

In a reduceRight (or reduce), there is 2 arguments

  1. A callback
  2. 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,

  1. The accumulator (what we returned (each) last time, init or last/first value for the first time)
  2. Each entry (from second last/second depending on init value passed or not)
  3. Current index
  4. 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);

You could use a closure over a count c and check this values and decrement and take the value with a logical AND &&.

This proposal uses Array#reduceRight, as wanted.

var array = [1, 2, 3, 4, 5],
    sum = array.reduceRight((c => (s, v) => s + (c && c-- && v))(3), 0)

console.log(sum);

x = [1,2,3,4,5];
n = 3; // How many numbers to take
console.log(x.slice(-n).reduceRight((prev, curr) => prev + curr, 0))

reduceRight takes two arguments: a callback and the initial value. We initialise it to 0 as we are counting.

curr in my example will be 3, then 4 then 5. prev will be 0, then 3, then 7.

See: Array.ReduceRight

var n = 4;
var x = [1, 2, 3, 4, 5];

var y = x.reduceRight(function(accumulator, currentValue) {
  if (n > 0) { // If n = 0, stop calculating the sum.
    accumulator += currentValue;
  }
  n--; // Reducing n value for every loop.
  return accumulator;
}, 0);

console.log(y);

Pretty simple :

var x = [1,2,3,4,5];
var n = 2;
var y = x.reduceRight((accumulator, currentValue, index) =>{
          if(index < x.length-n) return accumulator;
          return accumulator + currentValue;
       }, 0);

console.log(y);

https://developer.mozilla/de/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight

has a good example on almost exactly that.

const elementCountToLeaveOut = 3;

console.log([1,2,3,4,5].reduceRight((acc, val, idx) => idx >= elementCountToLeaveOut ? acc + val : acc))

You can try this logic:

  • Create a variable of final index(fIndex) where the loop should end.
  • Then you can loop using reduceRight and check if passed index is smaller then fIndex
    • If yes, return last calculated value
    • If no, return sum value.

function sumRight(arr, n) {
  var fIndex = arr.length - n;
  return arr.reduceRight(function(sum, num, index) {
    return index < fIndex ? sum : sum + num
  }, 0)
}

var x = [1,2,3,4,5]
console.log(sumRight(x, 3))

Something like this one

lastN=(x,n)=>(m=x.length-n,x.reduceRight((a,v,i)=>{return a+=i>=m?v:0;},0))

本文标签: javascriptHow to calculate sum of last n elements of an array using ArrreduceRightStack Overflow