Javascript:取数组的每个第 n 个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33482812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: take every nth Element of Array
提问by EsoMoa
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?
我得到一个数据数量未知的数组。但是我只有预定义的数据量要显示/存储。如何获取初始数组的每个第 n 个元素并在 JavaScript 中减少它?
Eg.: I get an Array with size=10000, but are only able to show n=2k Elements.
例如:我得到一个大小为 10000 的数组,但只能显示 n=2k 元素。
I tried it like that: delta= Math.round(10*n/size)/10 = 0.2 -> take every 5th Element of the initial Array.
我这样试过: delta= Math.round(10*n/size)/10 = 0.2 -> 取初始数组的每 5 个元素。
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?
对于 0.2,它始终为 0,但对于其他一些增量 (0.3),它可以正常工作。delta=0.4 也一样,我工作,但每隔一个 Element 就会被占用。我该怎么做才能让它发挥作用?
回答by Anonymous0day
Maybe one solution :
也许一种解决方案:
avoid filter because you don't want to loop over 10 000 elements ! just access them directly with a for loop !
避免使用过滤器,因为您不想循环超过 10 000 个元素!只需使用 for 循环直接访问它们!
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);
回答by nicholas
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.
将 newArr 设置为 oldArr 中每隔三个值。
回答by ericbn
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
如果您想arr
成为 的 1/2 ,则为 2,如果您想成为 的 1/3 oldArr
,则为 3,oldArr
依此类推。
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.
您正在调用循环内的filter()
每个元素,oldAdd
并且您应该调用filter()
整个数组以获取新的过滤数组。