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

Tips for effectively highlighting search text within HTML content without causing any issues

I am in search of a solution that can assist me in searching for specific terms within an HTML string while also highlighting them. I have the ability to remove the HTML content from the string, but this poses the problem of losing the context of the origi ...

Utilizing AJAX to send a parameter to PHP for processing

I am facing an issue with a script that is supposed to send data to a PHP file when a user clicks on an element, but unfortunately, it's not functioning correctly. Below is the jQuery code: jQuery( document ).ready(function( $ ) { $('.rve_b ...

In PHP, utilizing a for loop to create an array and then employing a separate for loop to manipulate that array

Within my for loop, I am creating two arrays: foreach ($data as $key => $value) { ........ ........ $user_insert[] = [ 'keyy' => $value, 'key' => $value, .... ... ... ]; $someArray1[ ...

The error message says: "VueComponent.filterKategori function cannot read property 'filter' because it is undefined at line 16260 in app.js."

this is the code snippet that I'm dealing with: computed: { filterKategori() { var kategori = this.kategori.data.filter(f => { return f.induk == null && f.id_klasifikasi == this.id_klasifikasi; }); return kat ...

Exploring the Contrast between 'this' Context in V8 Javascript: Chrome versus Node.js

Check out the code snippet below: var pocket = { cash: 1000, showCash: function() { return this.cash; } }; var thomas = { name: "Thomas", work: function() { console.log('I don&bs ...

invoking a function from two separate pages

I have created a React web app that is supposed to hide the navigation bar on the login page and then display it again after a successful login on all other pages. I achieved this by creating a function in App.js, but the issue arises when trying to call t ...

What is the best way to retain selection while clicking on another item using jQuery?

There is a specific issue I am facing with text selection on the page. When I apply this code snippet, the selected text does not get de-selected even after clicking .container: jQuery('.container').on("mousedown", function(){ jQuery('. ...

Automatically switch tabs upon pressing/scanning the Return key (using PHP, MySQL, and JavaScript)

Seeking assistance to resolve an ongoing issue that has been troubling me for the past few weeks. I am maintaining a basic web-based database to keep track of product serial numbers leaving our warehouse. The system is secure behind our firewall, so I&apo ...

Continuously update scrolling functionality

Could you please provide more information about the solution mentioned in the following question? I am facing a similar issue. jQuery’s css() lags when applied on scroll event Regarding solution #3 ->> To ensure continuous updates, it is suggested to t ...

What is causing the bullets for the unordered list to appear before the items are inserted into the list?

Can you explain why the bullets are showing up before the list items are added? <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>To Do List</title> </head> <body> ...

Updating row color according to values obtained from the map function in ReactJs

I have been experimenting with various methods to change the color of table rows based on specific values within a map function. Despite trying solutions like the UseRef hook and browsing through stack overflow, I have yet to achieve success. {dat ...

Acquire the selected option's value and display it within a div container

Is there a way to extract and display only the price value (after the " - ") within a div with the id of "price", updating as the select element is changed? <select id="product-select" name=""> <option value="1">Product Name / Yellow / S - ...

Combine div elements with identical class

Is there a way to utilize jQuery in order to enclose groups of elements with the same class within a div? I have been searching for a solution, but haven't found one yet. Here's an example of the HTML: <div class="view-content"> < ...

Client.on facing issue with receiving data upon initial connection

Currently, I am utilizing the net module in order to establish a connection between my client and server. Below is the code snippet: const Net = require('net'); client = Net.connect(parseInt(port), host, function() { co ...

CSS grid challenges on a massive scale

My CSS grid timeline is currently generating around 1300 divs, causing performance issues. Is there a way to style or interact with the empty nodes without rendering all of them? I also want each cell to be clickable and change color on hover. Any suggest ...

How to eliminate an item from an array using index in JavaScript with jQuery

In order to remove a specific array added in an object by index, I would like the functionality where when a user clicks on a button, it removes the corresponding array. Here's what I have in mind: HTML: <button>1</button> <button>2 ...

At times, the Ajax response may be lacking in content. However, the response tab in Google

My goal is to retrieve responses from an AJAX call and store them in the global scope for easy access throughout my website. var getOrderStatus = getOrderStatus(), getUserData = getUserData(), orderFormReady = $.when(getOrderStatus, getUserData), ...

Utilizing ng-class for dynamic routing and controlling

I am currently in the process of developing a dynamic framework using AngularJS. My plan involves allowing users to add new templateUrl and controller from a JSON file, like the one shown in templates.json: { "pages" : [ { "name" : "home" ...

Postpone the inclusion of html files within ng-include in AngularJS

I need to optimize the startup performance of my app by delaying the loading of a series of HTML files that are being included into my main controller. These files are not needed for at least 4 seconds while one specific HTML file processes. How can I de ...

angular: setting default selected items in dynamically generated options

After looking at the example provided here, I noticed that all three select options have the same value. How can I ensure that each option has a different selected value? This is what I currently have: <li ng-repeat="tarea in tareas"> <inp ...