Home > Enterprise >  How to take every nth continuous elements from an array?
How to take every nth continuous elements from an array?

Time:04-28

Im a bit new to javascript and my goal is to take every 3 elements in my array and store them as an array to be pushed to another array. Below is what this would look like

var a = [11, 2, 3, 4, 5, 6, 7, 8, 9, 2, 2, 3, 4, 5, 4];

Output would be

var arrays = [[11, 2, 3], [4, 5, 6], [7, 8, 9], [2, 2, 3], [4, 5, 4]]

These are just integers, but in my application, there is an array containing 73 objects which id like to store like this.

var objects = [{}, {}, {}], [{}, {}, {}] ,,,]

would there be any problems based on the number of objects as 73 is not divisible by three

CodePudding user response:

Something like this, the objects are abitrary here. I'm using .slice to get each next group of 3, and pushing it onto the buffer array. I'm using .length as my bound in the for loop and incrementing by 3 each time.

var a = [
  {x:11}, {x:2}, {x:3}, {x:4}, {x:5}, {x:6}, {x:7}, 
  {x:8}, {x:9}, {x:2}, {x:2}, {x:3}, {x:4}, {x:5}, {x:4}
];

buffer = [];
for(i=0; i<a.length; i =3) {
  buffer.push(a.slice(i, i 3));
}
console.log(buffer);

Also, slice can handle arrays that aren't divisible by 3. You can see in this example the leftover object is in its own array.

var a = [
  {x:11}, {x:2}, {x:3}, {x:4}, {x:5}, {x:6}, {x:7}, 
  {x:8}, {x:9}, {x:2}, {x:2}, {x:3}, {x:4}, {x:5}, 
  {x:4}, {x:112}
];

buffer = [];
for(i=0; i<a.length; i =3) {
  buffer.push(a.slice(i, i 3));
}
console.log(buffer);

You can also easily adapt to any n elements:

var a = [
  {x:11}, {x:2}, {x:3}, {x:4}, {x:5}, {x:6}, {x:7}, 
  {x:8}, {x:9}, {x:2}, {x:2}, {x:3}, {x:4}, {x:5}, 
  {x:4}, {x:112}
];

let n = 4;
buffer = [];
for(i=0; i<a.length; i =n) {
  buffer.push(a.slice(i, i n));
}
console.log(buffer);

Let me know if this helps.

  • Related