What is the best way to extract every nth consecutive items from an array?

As a newcomer to javascript, I am looking to group every 3 elements in an array and save them as subarrays within another array. Below is an example:

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

The desired output would be:

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

In my specific project context, I have an array with 73 objects that I'd like to organize in a similar manner.

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

I wonder if there would be any difficulties arising from the fact that 73 is not evenly divisible by three.

Answer №1

Within this scenario, the elements are arbitrary. Utilizing .slice allows for the retrieval of each consecutive set of 3 objects which are then added to the buffer array. The loop is based on the length of the array with an increment of 3 in each iteration.

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);

The .slice function can handle arrays that do not have a length divisible by 3. As illustrated in the example, any remaining object will be stored in its own individual 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);

This approach can also be easily modified for any number of 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);

If you have any further questions or need clarification, feel free to reach out.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am eager to prevent my division element from shifting position

I have a program that controls the water level in a virtual bottle. By clicking a button, the water level can increase or decrease. However, the program does not automatically stop; it requires manual intervention to stop it. I need to modify it so that wh ...

What is the best way to assign one String array to another in Java without using built-in methods? (Note: I am working with input/output operations

My program is designed to open a .txt file within the project folder and read its lines. The file reading function appears to be working correctly, ruling out any I/O issues or problems with Swing (which I am also utilizing). However, I am encountering a ...

The Axios response is coming back as a null value

//I utilized the context API to fetch data here const [allProfiles, setAllProfiles] = useState(""); const fetchAllProfiles = async () => { const res = await axios.get("http://localhost:5000/api/all-profiles"); setAllProfiles(res.data); }; ...

Whenever Ionic is paired with LokiJS, it consistently results in the error message: "ionic.bundle.js:26794 TypeError: Cannot read property 'insert' of undefined"

Having faced numerous issues with SQLite, I decided to explore LokiJS as an alternative solution for my Ionic app. However, even with LokiJS, I encountered challenges. Currently, I have a simple code that should function smoothly: .controller('Proje ...

The v-on:click functionality seems to have become unresponsive after being dynamically added through modifying the inner

While attempting to create a dynamic navbar, I encountered an issue. The goal was to have the navbar switch from displaying "login" and "register" when a session is logged in, to showing "profile" and "logout". The buttons for login and register were fun ...

Deciding whether an array forms a chain of factors

I am curious about the reasons why this code is failing some of the tests provided. It deliberately avoids using any ES6 code. Here is the given prompt: *A factor chain can be defined as an array where each preceding element serves as a factor for the su ...

What could be causing this JavaScript/CSS animation to only function on the initial instance and not the subsequent ones?

I've been attempting to apply this transition effect to multiple circles, but only the first one triggers it no matter where they are positioned on the page. javascript let circles = document.querySelectorAll('.circle') circles.forEach(cir ...

Releasing memory allocated for struct.name (warning: HEAP CORRUPTION IDENTIFIED)

Having an issue while attempting to free memory allocated with malloc in dynamic arrays created based on the length of a user-inputted name. The "Debug error" occurs when I try to use the free() function. typedef struct { char *nombre; float nota; ...

Problem with Selenium WebDriver: Some HTML elements are not being displayed

I am currently working on a python web scraper. Here is the code I have written: from selenium.webdriver.chrome.options import Options from selenium import webdriver from bs4 import BeautifulSoup chrome_options = Options() chrome_options.add_argument(&qu ...

Automatically fill in form fields with data from a JSON file as soon as the user enters a value

How can I retrieve the bank name, branch, city, and district from a JSON array? Below is the contents of my results.json file: { "ifsc": [{ "ifsc": "PUNB0000100", "bank": "PUNJAB NATIONAL BANK", "city": "ABOHAR ...

What is the best way to capture user input using an onClick event in JavaScript and then display it on the screen?

I'm in the process of upgrading a table, and while most of it is working fine, there is one function that's giving me trouble. I want this function to return an input with an inline onClick event. The actual return value is displaying correctly, ...

Node.js: Leveraging Express to Compare URL Parameters and Handle Delete Requests with Array Values

Having some issues with the Express routes I set up for an array of objects and CRUD operations. Everything works smoothly except for the "Delete" operation. I am trying to delete an object by matching its URL parameter ID with the value of its key. Howev ...

Ways to initiate SVG animations using Angular Component functions?

I am currently working on a project where I want to incorporate an animation that reflects the sorting process of an array of numbers. However, despite successfully sorting the numbers in the array, I am facing challenges with triggering the animations. I ...

having difficulty sending a post request with Angular

Submitting form data via HTTP post will look like this: saveDataFile(mutlidata,id,value): Observable<Response> { var _url = 'http://xxxx.xxx.xxx'; var saveDataURL = _url + '/' + id; var _this = this; ...

Charting data with missing values in Google Charts

I have generated a line chart using php and json to load the data. The issue I am facing is that the chart displays NULL values as 0, which does not look good. My assumption is that I may be formatting the json incorrectly, and what I really need is {"v" ...

What is the best way to divide the various arrays within my php variable?

After running this foreach loop, the variable contains multiple arrays. However, I would like to print just one array instead of printing them all separately. Foreach Loop Code: foreach ($finalpagesID as $value) { $IDjsonPage = json_decode( f ...

Using ReactJS to trigger a timer function on a button click

Kindly Note: This is a unique query and not related to ReactJS - Need to click twice to set State and run function. The suggested solution there does not resolve my issue. This represents my original state: constructor(props) { super(props) this. ...

Creating Dynamic Buttons in Laravel with AJAX and jQuery

Hello, I need help creating dynamic buttons as I am not familiar with ajax or jquery. I currently have a dynamic button running, but I want to create another dynamic button after I add another form. Here is my code. Please take a look at my image, as I am ...

checkbox revision

I'm attempting to update some text indicating whether or not a checkbox is checked. The issue is that when the checkbox is checked, the textbox disappears and the text takes its place. <form name="myForm" id="myForm"> <input type="checkb ...

What is the process for assigning default values to dynamically generated form elements?

I have been working on building a single-page application (SPA) using JavaScript and jQuery. During the process, I encountered an issue with a dynamic form. The user is able to add specific fields as needed, but if they don't generate and utilize all ...