简体   繁体   English

JS 均匀地减少一个数组

[英]JS Reduce an array evenly

I want to reduce this array down to 5 numbers, but as evenly as possible.我想将此数组减少到 5 个数字,但要尽可能均匀。 So I would need the start number, the end and then some in the middle.所以我需要开始编号,结束编号,然后是中间的编号。

const range = [8000, 9000, 10000, 11000, 12000, 13000, 14000, 15000, 16000, 17000, 18000, 19000, 20000, 21000, 22000, 23000, 24000, 25000, 26000, 27000, 28000, 29000, 30000]

Basically the above array is a data set for a slider I have, I want to show the numbers below so the user can see where to slider the slider too, however there are too many numbers to display nicely.基本上,上面的数组是我拥有的滑块的数据集,我想显示下面的数字,以便用户也可以看到滑动滑块的位置,但是有太多的数字无法很好地显示。

No idea how to do this, here is my attempt but is results in strangely spaced numbers due to not being even.不知道如何做到这一点,这是我的尝试,但由于不是偶数,结果是奇怪的间隔数字。

const steps = range[range.length - 1] / 5;
const start = range[0];
const stop = range[range.length - 1];

let marks = Array(Math.ceil((stop - start) / steps)).fill(start).map((x, y) => x + y * steps);
marks.push(stop);
console.log(marks);

Since you're using the first and last values, only 4 steps will actually be taken to receive 5 values (n-1).由于您使用的是第一个和最后一个值,因此实际上只需要 4 个步骤来接收 5 个值 (n-1)。 Let steps be a fractional value representing how many indices to step over between each iteration, starting at 0 and stopping at the highest index in the array.steps是一个小数值,表示在每次迭代之间要跨越多少个索引,从 0 开始并在数组中的最高索引处停止。

 const range = [8000, 9000, 10000, 11000, 12000, 13000, 14000, 15000, 16000, 17000, 18000, 19000, 20000, 21000, 22000, 23000, 24000, 25000, 26000, 27000, 28000, 29000, 30000] const values = 5; const steps = (range.length-1) / (values-1); let marks=[]; for(let i=0; i<values; i++){ console.log("Fractional index", i*steps); //just for display purposes marks.push(range[Math.round(i*steps)]); } console.log(marks);

Divide your range by n steps.将您的范围除以 n 步。 Then step through the list and add the values at each step.然后逐步遍历列表并在每一步添加值。

 const n=5; const range = [8000, 9000, 10000, 11000, 12000, 13000, 14000, 15000, 16000, 17000, 18000, 19000, 20000, 21000, 22000, 23000, 24000, 25000, 26000, 27000, 28000, 29000, 30000] const steps = Math.floor(range.length / n); const stop = range[range.length - 1]; let marks=[] for(let i=0;i<n-1;i++){ marks.push(range[i*steps]) } marks.push(stop) console.log(marks);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM