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?

2
  • Why can you not do var result = 0; for (var i = 0; i<plan.length; i++){ result += plan[i] * months[i]; } console.log(result) Commented Jan 4, 2016 at 7:39
  • How can I multiple index of each array? Commented Jan 4, 2016 at 7:40

4 Answers 4

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 );
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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]));

Comments

0

In ES6:

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

where sum is

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.