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?
4 Answers 4
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 );
Comments
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
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
In ES6:
sum(plan.map((e, i) => e * months[i])
where sum is
function sum(a) { return a.reduce((x, y) => x + y); }
var result = 0; for (var i = 0; i<plan.length; i++){ result += plan[i] * months[i]; } console.log(result)