0

How can I store each value of javascript array in variable such that I can use it to perform further actions?

Eg:

var plan = [100, 200];
var months = [3, 6];

for (var i = 0; i < plan.length; i++) {
    p_det = plan[i];
}
for (var i = 0; i < months.length; i++) {
    m_det = months[i];
}
console.log(p_det * m_det); //Gives me value of 200*6 

Mathematical action I've to perform such that ((100 * 3) + (200 * 6))

Is storing each value in variable will help? How can I achieve this?

Nehil Mistry
  • 1,101
  • 2
  • 22
  • 51

4 Answers4

1

Storing each element in a variable won't help, you already can access those values using the array[index]. Assuming your arrays are the same length, you can calculate what you want in a loop:

for (var sum = 0, i = 0; i < plan.length; i++) {
    sum += plan[i]*month[i];
}
console.log( sum );
Paul
  • 139,544
  • 27
  • 275
  • 264
1

you can achieve it with reduce assuming that both arrays have same length

var plan = [100, 200];
var months = [3, 6];

var sum = plan.reduce(function(sum, val, index) {
  return sum + months[index] * val;
}, 0);

snippet.log(sum)
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Bek
  • 3,157
  • 1
  • 17
  • 28
0

A simple while loop will do. It works for any length, because of the Math.min() method for the length.

function s(a, b) {
    var i = Math.min(a.length, b.length),
        r = 0;
    while (i--) {
        r += a[i] * b[i];
    }
    return r;
}

document.write(s([100, 200], [3, 6]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

In ES6:

sum(plan.map((e, i) => e * months[i])

where sum is

function sum(a) { return a.reduce((x, y) => x + y); }