简体   繁体   中英

How do I create (d) elements arrays out of another array of (n > d) elements?

For example, we have the array:

let arr = [1,2,3,4,5,6,7,8,9] //(n = 9)

Now i want to create maximum amount of arrays of d = 5:

Array1: arr1 = [1,2,3,4,5]

Array2: arr2 = [2,3,4,5,6]

Array3: arr3 = [3,4,5,6,7]

Array4: arr4 = [4,5,6,7,8]

Array5: arr5 = [5,6,7,8,9]

How can I do that?

Simple for loop and array.slice should work in this case:

 let arr = [1,2,3,4,5,6,7,8,9]; let d = 5; let result = []; for(let i = 0; i <= (arr.length - d); i++){ result.push(arr.slice(i, d+i)); } console.log(result);

I will assume that you want to keep your "sub-arrays" in the same order as your initial array?:

 const arr = [1,2,3,4,5,6,7,8,9]; console.log(generateSubArrs(arr, 5)); function generateSubArrs(arr, d){ const outputArrs = []; const n = arr.length; for (let i = 0; i <= (n - d); i++){ const tempArr = []; for (let j = 0; j < d; j++){ tempArr.push(arr[i + j]); } outputArrs.push(tempArr); } return outputArrs; }

Output:

[
  [    1,    2,    3,    4,    5  ],
  [    2,    3,    4,    5,    6  ],
  [    3,    4,    5,    6,    7  ],
  [    4,    5,    6,    7,    8  ],
  [    5,    6,    7,    8,    9  ]
]

One more solution using a reducer:

 const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] const size = 5 const result = arr.reduce((acc, _, i) => { if (i <= arr.length - size) acc.push(arr.slice(i, i + size)) return acc }, []) console.log(result)

Caveat: if size > arr.length , result will be an empty array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM