[removed] take every nth Element of Array

前端 未结 4 1424
梦谈多话
梦谈多话 2020-12-03 16:55

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 redu

相关标签:
4条回答
  • 2020-12-03 17:21

    Try

    arr = oldArr.filter(function (value, index, ar) {
        return (index % ratio == 0);
    } );
    

    where ratio is 2 if you want arr to be 1/2 of oldArr, 3 if you want it to be 1/3 of oldArr and so on.

    ratio = Math.ceil(oldArr.length / size); // size in the new `arr` size
    

    You were calling filter() on each element of oldAdd inside a loop and you're supposed to call filter() on the whole array to get a new filtered array back.

    0 讨论(0)
  • 2020-12-03 17:27

    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.

    0 讨论(0)
  • 2020-12-03 17:42

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

    0 讨论(0)
  • 2020-12-03 17:43

    Borrowing from @anonomyous0day's solution, generate a new Array with the desired indices from the given array:

    (Take every 3 items)

    Array.prototype.take = function(n) {
      if (!Number(n) && n !== 0) {
        throw new TypeError(`Array.take requires passing in a number.  Passed in ${typeof n}`);
      } else if (n <= 0) {
        throw new RangeError(`Array.take requires a number greater than 0.  Passed in ${n}`);
      }
    
      const selectedIndicesLength = Math.floor(this.length / n);
      return [...Array(selectedIndicesLength)].map((item, index) => this[index * n + 1]);
    };
    
    [1, 2, 3, 4, 5, 6, 7, 8].take(2); // => 2, 4, 6, 8
    
    0 讨论(0)
提交回复
热议问题