-2

I have an array which looks like this:

0: 0
1: 1
2: 2
3: 3
4: 4
5: 5
6: 6
7: 7
8: 8
9: 9
10: 10
11: 11
12: 12
13: 13
14: 14
15: 15
16: 16
17: 17
18: 21
19: 22
20: 23

I want to subtract each value with the next and save that subtracted value how do I do that

So far I have done this

    _this.elements.forEach(function (element, index) {
        console.log(parseInt(element) - parseInt(element[index])); 

    });

But it keeps returning undefined

Jon not doe xx
  • 533
  • 3
  • 10
  • 20
  • Reading how forEach works would help. Please refer [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) – Ms.Tamil Nov 12 '18 at 10:27
  • Can you please provide the complete code so that we can help? – Ahmed Hammad Nov 12 '18 at 10:27
  • For each doesn't return anything. Consider using `reduce`? – evolutionxbox Nov 12 '18 at 10:27
  • please add the result as well. why do you use the index as value, if talk about values of an array? please add the array in literal notation. – Nina Scholz Nov 12 '18 at 10:33
  • it looks to me like `element` is an object or nested array and you're trying to parse it as an **int**, now whatever it is you're trying to do, well is not clear, you need to let us know exactly what it is you want to do and what is it for, do you want to keep the original value and the value after subtracting it or do you want to replace the original for the new or....... – Bargros Nov 12 '18 at 10:34

2 Answers2

2

You could map a sliced array from the second element and map the delta of value of the original array at the same index with the value of the sliced array.

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 21, 22, 23],
    result = array.slice(1).map((v, i) => v - array[i]);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Read the documentation on forEach

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

forEach is a consumer method which will not return any result but just consume it each value of the array for particular purpose, like you did for display

coming back to your question i think best method to use is a reduce

    var numbers = [10, 1, 5];
    let result numbers.reduce( (v1,v2) => v1 - v2);
Navin Gelot
  • 1,264
  • 3
  • 13
  • 32