Javascript: take every nth Element of Array

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

Leave a Comment

deneme bonusu veren sitelerbahis casino