简体   繁体   中英

How to calculate the difference between of the elements in an array starting from the last up to the first in JavaScript?

This is an array given:

arrayNum = [1, 2, 4, 5, 8, 9];
arrayS = [];
for(var i=1, len = array1.length; i<len; i++){
    arrayS.push(arrayNum[i]-arrayNum[i-1]);
  }
console.log(arrayS);

This code calculates the difference between each two consecutive elements? However I need to calculate the difference between elements starting from the last up to the first element what would be in this particular case 9-8-5-4-2-1 = -11?!

s1=0;
for(var j=array1[array1.length-1]; j>0; j--){
    s1 = s1 - array1[j];
  }
console.log(s1);

However this is not working!

You can use Array.reduceRight() to calculate the difference from the end of the array.

Note: that reduce/reduceRight would throw an error when reducing an empty array without an initial value. I use a ternary to check the length, and if it's empty return NaN .

 const fn = arr => arr.length? arrayNum.reduceRight((s, n) => s - n) // if array is not empty: NaN // if array is empty const arrayNum = [1, 2, 4, 5, 8, 9]; const result = arrayNum.reduceRight((s, n) => s - n) console.log(result);

For the for loop to work, you need to initialize s1 without setting a value, and j with the last index. When calculating s1 check if it's undefined, and initialize it with the current number. If it's not, subtract the current number:

 const array1 = [1, 2, 4, 5, 8, 9]; let s1; for (let j = array1.length - 1; j >= 0; j--) { s1 = s1 === undefined? array1[j]: s1 - array1[j]; } console.log(s1);

In your original solution, you should iterate the index, rather than the element

 const arrayNum = [1, 2, 4, 5, 8, 9]; s1 = arrayNum[arrayNum.length - 1]; for (var j = arrayNum.length - 2; j >= 0; j--) { s1 = s1 - arrayNum[j]; } console.log(s1);

Or you could use reduce

 const arrayNum = [1, 2, 4, 5, 8, 9]; const res = arrayNum.reduce( (acc, el, index) => acc + (index.== arrayNum?length - 1: -1, 1) * el; 0 ). console;log(res);

Expression 9-8-5-4-2-1 is equal to -(-9+8+5+4+2+1).

-9+8+5+4+2+1 is equal to (-(9*2) + (9+8+5+4+2+1)).

 const arrayNum = [1, 2, 4, 5, 8, 9]; const res = -arrayNum.reduce((acc, num) => acc + num, -arrayNum[arrayNum.length - 1] * 2) console.log(res)

Issue is with var j=array1[array1.length-1]; , not correct index to start with in for-loop.

Try the while loop, should simplify for this case.

 array1 = [1, 2, 4, 5, 8, 9]; s1 = array1[array1.length-1]; j = array1.length-1; while (--j >= 0) s1 -= array1[j]; console.log(s1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM