Finds all arrays of consecutive elements.
- Use
Array.prototype.slice()
to create an array withn - 1
elements removed from the start. - Use
Array.prototype.map()
andArray.prototype.slice()
to map each element to an array ofn
consecutive elements.
代码实现
const findConsecutive = (arr, n) =>
arr.slice(n - 1).map((v, i) => arr.slice(i, i + n));
findConsecutive([1, 2, 3, 4, 5], 2);
// [[1, 2], [2, 3], [3, 4], [4, 5]]
翻译自:https://www.30secondsofcode.org/js/s/arrays-of-consecutive-elements