Julian Julian - 6 months ago 27
Javascript Question

How do you divide each number in an array by a variable in javascript?

I need a simple way to divide all the numbers (contained in objects) in an array by a variable in javascript (no jquery or other libraries) :

var divisor = 16;
var array = [{"x":0,"y":16},{"x":16,"y":32},{"x":32,"y":48}];


Expected Result:

[{"x":0,"y":1},{"x":1,"y":2},{"x":2,"y":3}];


Any ideas ?

Answer Source

This should do it for you:

var divisor = 16;
var array = [{"x":0,"y":16},{"x":16,"y":32},{"x":32,"y":48}];

for(var i = 0, length = array.length; i < length; i++){
    array[i] = {'x':array[i].x/divisor,'y':array[i].y/divisor};
}

In case you are likely to extend the objects in the future, you might want to do it like this, instead:

for(var i = 0, length = array.length; i < length; i++){
    array[i].x /= divisor;  // `a[i].x /= d` is shorthand for `a[i].x = a[i].x / d`
    array[i].y /= divisor;
}

This has the advantage that it doesn't overwrite array[i], saving possible other properties.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download