I'm trying to get sequential values from a dynamically generated array of numerical values, and add those sequential values together in pairs, in sequence. The generated array will always have an even number of values. As an example, let's say the array comes out to
myArray = [2, 23, 45, 128, 92, 3].
How can I use jQuery to iterate over the generated array and get values like this?
val1 = myArray[0] + myArray[1];
val2 = myArray[2] + myArray[3];
val3 = myArray[4] + myArray[5];
The array is dynamically generated, and as the list of items may increase or decrease, I don't want to hardcode existing key/values. I need to come up with a formula that will take into account the future addition or subtraction of the sequential pairs.
Any help would be greatly appreciated!
4 Answers 4
var result=[];
for(var i=0,limit=myArray.length; i<limit; i+=2)
{
result[i]=myArray[i]+myArray[i+1];
}
Comments
I would do it like this,
var newArry = [], tmp, myArray = [1,2,3,4,5];
myArray.forEach(function(v,i){
if(i%2>0){
newArry.push(tmp+v);
}
tmp = v;
});
console.log(newArry);
3 Comments
$.each(), jsfiddle.net/2xxkhLqx, foreach is (v,i), $.each it is (i,v)You can't use dynamic variable names like that so try
var myArray = [2, 23, 45, 128, 92, 3],
obj = {};
for (var i = 0; i < myArray.length / 2; i++) {
obj['val' + (i + 1)] = myArray[i * 2] + myArray[i * 2 + 1]
}
console.log(obj)
Comments
Use .each(...) function of a jQuery do a magic for you.
var val = 0;
var myArray = [2, 23, 45, 128, 92, 3];
$.each(myArray, function( index, value ) {
val = (index % 2 === 0 )? value : val + value;
if (index % 2 !== 0 )
console.log( val);
});
You can check index value for even / odd and apply your logic here...
PS: The above will show the output in the console box of your browser.
Working Demo: http://jsbin.com/qivesekono/1/