Intrepidity
Intrepidity

Reputation: 103

How to divide a number by every number in an array?

Let's say x = 120, and you have an array: [1,2,3,4,5].

Id like to create an array that has the results of 120 divided by every number in the array individually, so it produces

[120, 60, 40, 30, 24]?

Upvotes: 0

Views: 1906

Answers (3)

Lex
Lex

Reputation: 184

Use Array.prototype.map

var dividend = 120;
var divisors = [1,2,3,4,5];

ES5

var quotients = divisors.map(function(divisor){
    return dividend / divisor;
);

ES6

var quotients = divisors.map(divisor=> dividend / divisor);

Upvotes: 1

Pineda
Pineda

Reputation: 7593

You could use Array.prototype.map

Using ES5:

var dividedBy120 = [1,2,3,4,5].map(function(currentValue, index, array){
  return 120/currentValue;
});
// dividedBy120 = [120, 60, 40, 30, 24]

Using ES6 arrow function:

var dividedBy120 = [1,2,3,4,5].map(currentValue => 120/currentValue);
// dividedBy120 = [120, 60, 40, 30, 24]

Upvotes: 3

Nicholas Smith
Nicholas Smith

Reputation: 720

You can do it like this:

 var array = [1, 2, 3, 4, 5];
 var division_results = []; // The results are stored here.

    for (var i = 0; i < array.length; i++){
        var result = 120 / array[i]; // This is the result of the division.
        division_results.push(result);
    }

Upvotes: 1

Related Questions