EsoMoa EsoMoa - 4 years ago 206
Javascript Question

Javascript: take every nth Element of Array

I get an Array with an unknown Number of data.
But I only have an predefined amount of data to be shown/store.
How can I take every nth Element of the initial Array and reduce it in JavaScript?

Eg.: I get an Array with size=10000, but are only able to show n=2k Elements.

I tried it like that:
delta= Math.round(10*n/size)/10 = 0.2 -> take every 5th Element of the initial Array.

for (i = 0; i < oldArr.length; i++) {
arr[i] = oldArr[i].filter(function (value, index, ar) {
if (index % delta != 0) return false;
return true;
});
}


With 0.2 it´s always 0, but with some other deltas (0.3) it is working. Same for delta=0.4, i works, but every second Element is taken with that. What can I do to get this to work?

Answer Source

Maybe one solution :

avoid filter because you don't want to loop over 10 000 elements ! just access them directly with a for loop !

 
var log = function(val){document.body.innerHTML+='<div></pre>'+val+'</pre></div>'} 

var oldArr = [0,1,2,3,4,5,6,7,8,9,10]
var arr = [];

var maxVal = 5;

var delta = Math.floor( oldArr.length / maxVal );

// avoid filter because you don't want
// to loop over 10000 elements !
// just access them directly with a for loop !
//                                 |
//                                 V
for (i = 0; i < oldArr.length; i=i+delta) {
  arr.push(oldArr[i]);
}


log('delta : ' + delta + ' length = ' + oldArr.length) ;
log(arr);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download