Skip to content

Instantly share code, notes, and snippets.

@ekas
Created May 23, 2020 09:54
Show Gist options
  • Save ekas/901368cffa212495000262f194d7425a to your computer and use it in GitHub Desktop.
Save ekas/901368cffa212495000262f194d7425a to your computer and use it in GitHub Desktop.
// Creating subarrays for input array given based on variable size k.
// Example: Input: [8, 2, 4, 20] & k=2 it should output to[[8, 2], [2, 4], [4, 20]]

const subArr = (arr, k) => {
  return arr.map((a, i) => {
    return arr.slice(i, k + i).length === k ? arr.slice(i, k + i) : '';
  }).filter((a) => a.length);
}

console.log(subArr([8, 2, 4, 20,], 1))
console.log(subArr([8, 2, 4, 20,], 2))
console.log(subArr([8, 2, 4, 20,], 3))
console.log(subArr([8, 2, 4, 20,], 4))
console.log(subArr([8, 2, 4, 20,], 5))

Solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment