I want to subtract elements from an array in JS, but that returns several results

0

I want to subtract values from a array in JavaScript, but it is not a subtraction of a value from a given array

I want to do the following: I have an array any that brings me actual values from my bank. In this case I will put one to exemplify:

var arrayExemplo = [2, 5, 9, 10, 15];

I want to subtract

  • element 5 by element 2
  • element 9 by element 5
  • element 10 by element 9
  • element 15 by element 10

I want my output to go out

[3, 4, 1, 5]

How can I do this?

    
asked by anonymous 13.10.2017 / 15:34

4 answers

1

Just use a for that traverses the size of the vector and subtract the position i + 1 by position i

var arrayExemplo = [2, 5, 9, 10, 15];
var novoArray = [];
for(i = 0; i < arrayExemplo.length-1; i++)
{
  novoArray[i] = arrayExemplo[i+1]- arrayExemplo[i];
  console.log(novoArray[i]);
}
<h4>ArrayExemplo = [2, 5, 9, 10, 15]<h4>
    
13.10.2017 / 15:41
0
var arrayResultado = [arrayExemplo[1] - arrayExemplo[0],arrayExemplo[2]-arrayExemplo[1],arrayExemplo[3]-arrayExemplo[2],arrayExemplo[4]-arrayExemplo[3]];
    
13.10.2017 / 15:42
0

You can do it like this:

var arrayExemplo = [2, 5, 9, 10, 15];

function subtrair(arr) {
  return arr.reduceRight((res, el, i, arr) => {
    return (i == 0) ? res : res.concat(el - arr[i - 1]);
  }, []).reverse();
}

var resultado = subtrair(arrayExemplo);
console.log(resultado);

Using reduceRight iteras from the end of the initial array.

    
13.10.2017 / 15:43
0

Make a for, and do not forget to put an index check:

var arrayExemplo = [2, 5, 9, 10, 15];
var resultado = [];
for (i = 0; i < arrayExemplo.length - 1; i++) {
    resultado[i] = arrayExemplo[i + 1]- arrayExemplo[i];
}
    
13.10.2017 / 15:45