-1

am wonder how to do this one, can you help me to learn how to think and solve this kind of problem, please?

in this example i will use 8 like N

let original = [1,2,3,4,5,6,7,8,9,10];

//to 

let modified  = [[1,2,3,4,5,6,7,8],[9,10]]

for example if i use a Array.slice and i have more than the example number like 19 elements inside original i need to create a new array inside to modified

and should be look like this :

[[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16],[17,18,19]]

is dynamic

Hernan Humaña
  • 433
  • 5
  • 18
  • 1
    https://github.com/lodash/lodash/blob/master/chunk.js For a reference of how lodash does chunk, which is essentially what you are asking for – Taplar Mar 11 '21 at 23:23
  • @HernanHumaña - I've updated my answer if you care to take a look. My answer is much simpler than the lodash solution or the other provided answer. – Randy Casburn Mar 12 '21 at 00:09

2 Answers2

1

Use .slice() to pull out the parts needed.

You should read the docs for slice.

The way to think about this is "I want part of the array". In JavaScript you retrieve part of an array by using .slice().

Since you have an unknown number of elements, you can use a while loop and shorten the array on each loop. The loop should exit when there are less elements than the size you want (8). Then, add the remaining elements. All of this still using slice.

let original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19];
let out = [];
while (original.length > 8) {
  out.push(original.slice(0, 8));
  original = original.slice(8);
}
out.push(original);
console.log(out);
Randy Casburn
  • 13,840
  • 1
  • 16
  • 31
  • 1
    you are right! the problem is that is every 8 times that means that if in the next one is more than 8 numbers, should be create a new array in the ```out``` – Hernan Humaña Mar 11 '21 at 23:10
  • 2
    My answer is based upon your input. If you need an answer based upon different input parameters you should include the exact input that you are having difficulty with. I'll help you solve the problem if you state it clearly in your question. Please edit your question and provide the correct input. – Randy Casburn Mar 11 '21 at 23:12
  • answer has been updated to reflect your edited question. – Randy Casburn Mar 12 '21 at 00:11
0

I will do that this way:

let original_1 = [1,2,3,4,5,6,7,8,9,10]
  , original_2 = [1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19]


const arrayCut = (arr, count) => arr.reduce((a,c,i)=>
  {
  let aN = Math.floor(i/count)
  if (!(i%count)) a.push([])
  a[aN].push(c)
  return(a)
  },[])

let mod_1 = arrayCut( original_1, 8 )
  , mod_2 = arrayCut( original_2, 8 )

console.log('mod_1', JSON.stringify(mod_1))
console.log('mod_2', JSON.stringify(mod_2))
.as-console-wrapper { max-height: 100% !important; top: 0; }
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40