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

730 B

title, type, language, tags, author, cover, dateModified
title type language tags author cover dateModified
Map consecutive elements snippet javascript
array
chalarangelo cold-mountains 2021-08-08T05:00:00-04:00

Maps each block of n consecutive elements using the given function, fn.

  • Use Array.prototype.slice() to get arr with n elements removed from the left.
  • Use Array.prototype.map() and Array.prototype.slice() to apply fn to each block of n consecutive elements in arr.
const mapConsecutive = (arr, n, fn) =>
  arr.slice(n - 1).map((v, i) => fn(arr.slice(i, i + n)));
mapConsecutive([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3, x => x.join('-'));
// ['1-2-3', '2-3-4', '3-4-5', '4-5-6', '5-6-7', '6-7-8', '7-8-9', '8-9-10'];