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

Asked

Viewed 635 times

0

I’m trying to subtract values from a array in Javascript, but not a subtraction of a given value array on the other hand.

I want to do this: I have one array any that brings me real 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 for element 9
  • element 15 by element 10

I want my results to come out

[3, 4, 1, 5]

How can I do?

  • 1

    Isn’t it a complex task, what you’ve been trying to do? We can help you with the parts you doubt or didn’t get

4 answers

1

Just use a for which traverses the size of the vector and subtract the position i+1 by the 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>

0

var arrayResultado = [arrayExemplo[1] - arrayExemplo[0],arrayExemplo[2]-arrayExemplo[1],arrayExemplo[3]-arrayExemplo[2],arrayExemplo[4]-arrayExemplo[3]];
  • I didn’t give the -1 but your solution is too adapted to the example and won’t work if the initial array has more elements, or less elements.

  • This is not a proper Helder response, the user will be limited to this vector only. (also did not give -1)

  • I know I do, but the question can only be whether one can subtract elements of an array within another array. It gives the example in subtracts (i+1 - i) but if it wants to do random subtractions?

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 the reduceRight iterations of the end of the initial array.

0

Do a go, and don’t forget to put up 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];
}
  • 2

    You don’t need an if, just go through the for with a position less than the vector.

  • True, edited, thank you @Bsalvo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.