-2

I want solve a function called aperture which accept a number and an array that should return new array that should be composed of subarrays the size of the number with consecutive elements, for example aperture:

(3, [1, 2, 3, 4, 5]); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
Frak
  • 832
  • 1
  • 11
  • 32
  • 3
    What have you tried so far? What are the issues? – shrys Jul 04 '19 at 04:26
  • it doesn't work with any of the other examples, its my fault not to post all the examples: aperture(1, [1, 2, 3, 4, 5]); // [[1], [2], [3], [4], [5]] aperture(2, [1, 2, 3, 4, 5]); // [[1, 2], [2, 3], [3, 4], [4, 5]] aperture(3, [1, 2, 3, 4, 5]); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]] aperture(4, [1, 2, 3, 4, 5]); // [[1, 2, 3, 4], [2, 3, 4, 5]] aperture(5, [1, 2, 3, 4, 5]); // [[1, 2, 3, 4, 5]] – Mohamed Ammar Jul 19 '19 at 23:00

1 Answers1

1

Create an empty array whose length is equal to the given number and use reduce() on it.

const aperture = (num,arr) => [...Array(num)].reduce((ac,_,i) => {
  ac.push(arr.slice(i,num+i));
  return ac;
},[])

console.log(aperture(3,[1,2,3,4,5]))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73