zppinto
zppinto

Reputation: 297

Reduce and Sum Array positions

Lets say I have this array:

var likes = [4,7,3,11,3,73,78,34,7,13];

However, I'm only capable of use the length of 5 due to some restrictions. So I want to "convert" it to an array lenght of 5, and sum the other positions, by distribute them equally.

Does anybody have a clue how can I do this?

Upvotes: 0

Views: 160

Answers (3)

zppinto
zppinto

Reputation: 297

Finally, i think i found the answer! :) If you have any suggestion, please comment!

var likes = [1,2,3,4,5,6,7,8,9,10];
    result_array = [];
    result_array2 = [];    
    max = 8;

if (likes.length>max){
    result_array = likes;
    for (var i = 0; i < max; i++) {
            var res = (likes.length - max) / max
            var new_val = (result_array[i] + (result_array[i+1] * res));
            result_array2.push(new_val);

    }

result_array = [];
result_array = result_array2;

}else{
result_array=likes
}

alert(result_array);

Please check the code here

Upvotes: 0

MCL
MCL

Reputation: 4075

Since it is not very clear what you want exactly, I'll post an answer, too. This code will maintain a fixed length of 5 in your output array, no matter how large your input is.

var input = [4,7,3,11,3,73,78,34,25,7,13,19,2],
    max = 5,
    out = [];

var adjacentItems = Math.ceil(input.length / max);
for(var i=0; i<input.length; i += adjacentItems) {
    var aSum = 0;
    for(var j=i; j<Math.min(i+adjacentItems, input.length); j++) {
        aSum += input[j];
    }
    out.push(aSum);
}

Check out the fiddle

Upvotes: 1

BenM
BenM

Reputation: 53228

Maybe this will solve your problem:

var likes = [4,7,3,11,3,73,78,34,7,13],
    result_array = [ ];

for(var i = 0; i < likes.length; i++)
{
   if(i % 2)
   {
       var new_val = likes[i - 1] + likes[i];
       result_array.push(new_val);
   }
}

See a working jsFiddle here.

This will cause the new array to contain [ 11, 14, 76, 112, 20 ], and will similarly increase in length when new values are added to the initial array.

Upvotes: 1

Related Questions