Divide each element of an array

7

I have this array promedio = [220,230]; and to each I need to divide it by var cantidad = 4;

    
asked by Eduard 09.06.2017 в 16:38
source

3 answers

10

A simple example with array.map will generate a new array on which you are going to travel

const divisor = 4;
const array = [220, 320];
let  resultado = []
resultado = array.map(function(v) {
  return v / divisor;
});

console.log(array.toString(), "array de entrada");
console.log(resultado.toString(), "array de salida");
    
answered by 09.06.2017 / 17:00
source
5

You can go through your arrangement to access each of the elements and divide it by the number you need. I do not return an array or update the array elements because I imagine you will use them separately.

var promedio = [220,320];
var cantidad = 4;
for (i = 0; i < promedio.length; i++) { 
    var resultado = promedio[i] / cantidad;
    console.log(resultado);
}
    
answered by 09.06.2017 в 16:47
1

You have an answer with a loop and another with map , I'll give you a third using forEach . With forEach you cross all the elements of an array, then you only have to update the value:

var promedio = [220, 320];
var resultado = [];
var divisor = 4;

promedio.forEach(function(elemento, indice) {
   resultado[indice] = elemento / divisor;
});

console.log(resultado);
    
answered by 09.06.2017 в 17:10