Subtract varlores from one array with the last value of another array

0

I need to add to this subtraction tamaño -= parseInt(distanciaCentroUltimo[n]); the last element of otroArray that is 970 and divide it by 2 NOTE : the array that is named anotherArray can grow so that 970 will not always be the last element.

Let me explain: this subtraction tamaño -= parseInt(distanciaCentroUltimo[n]) gives me a result of tamaño = 895 , then at that 895 I must subtract it with the last value of otrosarray and divide it by 2 the cell must give me a final result of 410 size.

The mathematical operation would be like this: 4500-890-930-885-900 = 895 - 970 /2 = 410

This is what I have at the moment.

var distanciaCentroUltimo = [890,930,885,900];
var tamaño = 4500;
var otroArray = [920,850,970]; 

for ( n in distanciaCentroUltimo) {
    tamaño -= parseInt(distanciaCentroUltimo[n]);
};

console.log(tamaño);
    
asked by Eduard Zora 23.04.2017 в 18:22
source

1 answer

1

Based on your comment:

  

The mathematical operation would be like this: 4500-890-930-885-900 = 895 - 970/2 = 410

You only need to get the last element of otroArray and divide it by 2 to subtract this result from the size. You can do it by otroArray[otroArray.length - 1] or by slice . In terms of performance, the first form is subtly faster than the second:

var distanciaCentroUltimo = [890, 930, 885, 900];
var tamanio = 4500;
var otroArray = [920, 850, 970];

for (let distancia of distanciaCentroUltimo) {
  tamanio -= parseInt(distancia);
}

tamanio -= otroArray.slice(-1)[0] / 2;
console.info(tamanio)

You can also save the for and use reduce :

var distanciaCentroUltimo = [890, 930, 885, 900];
var tamanio = 4500;
var otroArray = [920, 850, 970];

tamanio -= distanciaCentroUltimo.reduce(function(acc, dist) {
  return acc + dist;
})

tamanio -= otroArray.slice(-1)[0] / 2;
console.info(tamanio)
    
answered by 23.04.2017 / 18:48
source