[英]JavaScript: a better way to extract every 5th item from an array
我有一个坐标元组数组,例如
[ [ 1, 1 ],
[ 2, 2 ],
[ 3, 3 ],
[ 4, 4 ],
[ 5, 5 ],
[ 6, 6 ],
[ 7, 7 ],
[ 8, 8 ],
[ 9, 9 ],
[ 10, 10 ]
...
我想将它们中的每第 5 个坐标提取到一个新数组中
这是我的实现
const coordinates = Array.from({ length: 30 }, (_, i) => [i + 1, i + 1]) const { filteredCoordinates } = coordinates.reduce( (accu, currCoordinate) => { if (accu.count === 5) { accu.filteredCoordinates.push(currCoordinate) accu.count = 1 } else { accu.count += 1 } return accu }, { count: 1, filteredCoordinates: [], } ) console.log(filteredCoordinates);
这工作正常,但我想知道是否有更好的方法来做到这一点?
您可以采用索引并将其增加所需的计数。
这种方法不会迭代整个数组,只会迭代想要的索引。
const coordinates = Array.from({ length: 30 }, (_, i) => [i + 1, i + 1]), filtered = []; for (let i = 4; i < coordinates.length; i += 5) filtered.push(coordinates[i]); console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
您可以根据给定索引的五的模数过滤数组。
const coordinates = Array.from({ length: 30 }, (_, i) => [i + 1, i + 1]) const everyFithCoordinate = coordinates.filter((_, i) => (i+1) % 5 === 0); console.log(everyFithCoordinate);
无需完全循环,您可以使用传统的for
循环并使用step
5 递增它
const coordinates = Array.from({ length: 30 }, (_, i) => [i + 1, i + 1]); const result = []; const step = 5; for (let i = step - 1; i < coordinates.length; i += step) { result.push(coordinates[i]); } console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */ .as-console-wrapper { max-height: 100% !important; top: 0; }
我想将它们中的每 5 个坐标提取到一个新数组中
根据您对“提取”的定义,您可能希望将这些坐标从第一个数组移动到第二个数组。 此示例使用for statement
。 我缓存长度,然后在给定索引处从数组中splice
出坐标,并将其推送到新数组中。 然后减少长度和索引,因为它们在下一次迭代之前已经改变。
const coordinates = Array.from({ length: 32 }, (_, i) => [i + 1, i + 1]); const out = []; const count = 5; let { length } = coordinates; for (let i = count - 1; i < length; i += count) { out.push(coordinates.splice(i, 1)[0]); --length; --i; } console.log(JSON.stringify(out)); console.log(JSON.stringify(coordinates));
使用Array.from()
完成此任务的正确且有效的功能方法。 然而,据我所知,到目前为止没有人正确实施它。 咱们试试吧。
var coords = Array.from({ length: 30 }, (_, i) => [i + 1, i + 1]), period = 5, result = Array.from( {length : ~~(coords.length / period)} , (_,i) => coords[i*period+period-1] ); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.