Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
How to take every nth continuous elements from an array?

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!