Files
30-seconds-of-code/snippets/js/s/consecutive-element-subarrays.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

753 B

title, type, language, tags, author, cover, dateModified
title type language tags author cover dateModified
Consecutive element subarrays snippet javascript
array
chalarangelo camera-zoom 2020-10-18T20:24:28+03:00

Creates an array of n-tuples of consecutive elements.

  • Use Array.prototype.slice() and Array.prototype.map() to create an array of appropriate length.
  • Populate the array with n-tuples of consecutive elements from arr.
  • If n is greater than the length of arr, return an empty array.
const aperture = (n, arr) =>
  n > arr.length
    ? []
    : arr.slice(n - 1).map((v, i) => arr.slice(i, i + n));
aperture(2, [1, 2, 3, 4]); // [[1, 2], [2, 3], [3, 4]]
aperture(3, [1, 2, 3, 4]); // [[1, 2, 3], [2, 3, 4]]
aperture(5, [1, 2, 3, 4]); // []