Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 869
EsoMoa Avatar asked Nov 02 '15 16:11

EsoMoa


People also ask

What is the index value of nth element of an array *?

Line 6 : int element = arr[n-1]; And we all know the array is index based that means index always starts with 0. So , the element present in at first position has index value is 0. arr[n-1] : Here inside the square bracket “[]” we give the index value .

How do I find the second element of an array?

To get the second to last element in an array, call the at() method on the array, passing it -2 as a parameter, e.g. arr.at(-2) . The at method returns the array element at the specified index.


2 Answers

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);
like image 199
Anonymous0day Avatar answered Sep 19 '22 03:09

Anonymous0day


Filter itself returns an array. If I'm understanding you correctly, you don't need that surrounding loop. So:

newArr = oldArr.filter(function(value, index, Arr) {     return index % 3 == 0; }); 

will set newArr to every third value in oldArr.

like image 37
nicholas Avatar answered Sep 21 '22 03:09

nicholas