What is the best way to divide an array into pairs and store them in separate arrays?

I'm attempting to challenge my JavaScript skills and faced with a dilemma.

There is an array containing data

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
.

The goal is to pair the elements and generate a new array of arrays such as

var newArray = [[1,2], [3,4], [5,6]];
etc

What would be the best approach to tackle this issue?

Answer №1

Let's create a new array by grouping every two elements from the original array. Here is the JavaScript code to achieve this:

var arr = [ 4, 1, 2, 8, 9, 0 ]
var newArray = []

for (var i=0; i<arr.length; i+=2) {
   newArray.push([arr[i], arr[i+1]])
}

console.log(newArray)

Answer №2

I have created a versatile function that is capable of handling various scenarios based on your needs. You have the option to configure it to accommodate any number of objects by simply passing in the parameter n.

const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function splitListByN(list, n = 2, reverse) {
  if(reverse) {
    return [list.splice(list.length - n).reverse()].concat(list.length > 0 ? splitListByN(list, n, reverse) : list);
  }
  return [list.splice(0, n)].concat(list.length > 0 ? splitListByN(list, n) : list);  
}

console.log(splitListByN(items, 3));

The function works by breaking down the initial list into smaller partitions. Each partition includes

[firstPartition, shortenedListFromRecursiveCall]
. For instance, with n set to 3, the output will be
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
. If no value is provided for n, it defaults to 2.

Furthermore, you can utilize the reverse feature:

console.log(splitListByN(items, 3, true))
. This would result in
[ [ 10, 9, 8 ], [ 7, 6, 5 ], [ 4, 3, 2 ], [ 1 ] ]

Answer №3

To achieve the desired chunk size, you can create a variable to store the size and an index to iterate over the elements until there are none left.

var array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
    size = 3,
    chunks = [],
    i = 0;

while (i < array.length) chunks.push(array.slice(i, i += size));

console.log(chunks);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

What's the best way to keep track of the number of objects I've created

Using this HTML code, I can create member objects. However, I also need to determine the count of these member objects for certain calculations. Additionally, when a member object is deleted, the count of member objects should be reduced accordingly. The ...

Is it possible to exchange code among several scripted Grafana dashboards?

I have developed a few customized dashboards for Grafana using scripts. Now, I am working on a new one and realizing that I have been duplicating utility functions across scripts. I believe it would be more efficient to follow proper programming practices ...

Using recursion in JavaScript to determine if a given number is prime

I am feeling a bit puzzled about how to tackle this issue. My goal is to have all prime numbers return as true, and if not, then false. I noticed that my current logic includes 2, which returns 0 and automatically results in false because 2 has a remainder ...

Node.js module mishap

In the package.json file I'm working with, these are the content of my dependencies: "devDependencies": { "chai": "^4.1.2", ... "truffle": "4.1.3" } A new NodeJS script called getWeb3Version.js was created: let web3 = require("web3" ...

A useful tip for emphasizing tags that have attributes with endings

Here is the HTML list I'm working with: <li class=​"info" data-info=​"" data-title=​"info 1" data-info-id=​"222643">…</li> <li class=​"info" data-info=​"" data-title=​"info 2" data-info-id=​"217145">…</li> ...

Utilizing PHP and Ajax for paginating JSON responses

I have successfully parsed some JSON data from the YouTube API, but I am running into a limitation where only 50 results can be shown per request. I am looking for help on how to implement pagination using either JavaScript or Ajax in my PHP script. The go ...

What is the process for writing code in a recursive manner?

I'm in the process of converting these code snippets into smaller ones using recursion. However, I've hit a roadblock while trying to implement a for loop. The dictionary I am working with is: var structure = []; and it has the following structu ...

JavaScript: A timer that relies solely on the concept of TIME

Hello all, I have a specific question regarding starting a timer in JavaScript for a test scenario. Despite researching on my own and seeking help on various platforms, I haven't found a solution that fits my requirements. I am looking to implement a ...

Oops! We couldn't locate or access the file you're trying to import: ~bootstrap/scss/bootstrap

Following the steps outlined on getbootstrap.com, I assumed that everything would function smoothly. Unfortunately, that hasn't been the case so far. All seems well until I attempt to load the page, at which point my Express.js app throws a: [[ ...

Show PHP results in an Ajax modal box

Hey everyone! I'm new to this and had some code written for me by a programmer. Unfortunately, I can't reach out to them for help anymore. I have a calculator that shows results (generated by calc.php) without refreshing the page. Check out the ...

What is causing this promise to fail?

Exploring the use of promises in a code example has left me puzzled. Despite my efforts to understand promises, my initial attempt failed and only outputted "Promise didn't work". Upon closer inspection, I realized that the hide() function taking 400 ...

What are some tips for incorporating vue.js into a basic web application?

I've been trying to incorporate vue.js into my web application, but for some reason, it's not loading and the HTML is not firing in the browser. Please take a look at the code snippet below: <!DOCTYPE html> <html> < ...

Is there a way to hide a paragraph or div using javascript?

I am experimenting with using buttons to hide paragraphs using javascript, but even when I set them as "hidden", there is still excess blank space left behind. Is there a way I can eliminate that extra space? Below is the javascript code: function backgro ...

Why does the event fail to trigger in an Angular 5 Kendo grid when the last character is deleted from the input box?

I have implemented a multi-filter in my Kendo Grid for an Angular 5 application. However, I am facing an issue where the event is not firing when the last character is deleted from the input box. How can I resolve this issue? For example, if I type ' ...

JavaScript and HTML - specify the location in the html document where the JavaScript script will be displayed

I'm a beginner when it comes to JavaScript. I am trying to make sure that my HTML page remains unchanged while JavaScript text is displayed in a specific location without refreshing the entire page. To trigger a JavaScript function via a button on a ...

The Next.js API endpoint is struggling to process cross-domain POST requests

Dealing with a POST request in my NextJS application has been challenging. This particular post request is originating from a different domain. To address this issue, I included a receptor.ts file in the /pages/api directory: import { NextApiRequest, Next ...

Strategies for transferring data between controllers and configuration files in AngularJS

I'm attempting to pass a variable to the angular js config, Here is my JavaScript app: var app = angular.module('myApp', ['ngMaterial', 'sasrio.angular-material-sidenav', 'ui.router']); app.controller('ba ...

Can you explain what is meant by an "out of DOM" element?

I'm feeling a bit lost when it comes to DOM nodes and all the terminology surrounding them. Initially, I believed that the DOM consisted solely of what I could see in my inspector - nothing more, nothing less. However, I've come across functions ...

Monitoring and recording Ajax requests, and retrying them if they were unsuccessful

As a newcomer to Javascript, I'm diving into the world of userscripts with the goal of tracking all Ajax calls within a specific website. My objective is to automatically repeat any failed requests that do not return a status code of 200. The catch? T ...

Attempting to modify the array content using useState, but unfortunately, it is not functioning as expected

Starting out with react.js and trying to update an array's content using useState upon clicking a send-button, but it's not working as expected. Struggling with adding date and number in the row. Check image here Here's what I'm aiming ...