What is the process for forming a series of arrays from one singular array?

If I have a large array consisting of numbers from 1 to 18, is there a simple method to split it into pairs like [1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13,14] for n=2? The special case of n=2 is all I need.

Answer №1

Here is a solution that should do the trick:

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

I came up with a more versatile approach that can handle any number of "pockets" or whatever you might call them. It takes care of handling undefined values for odd numbers of items:

Array.prototype.pockets = function(n) {

  let result = [],
      pocket = [],
      i, j;

  for (i = 0; i < this.length; i += n) {
    pocket.length = 0;
    for (j = 1; j < n; j++) {
      if (this[i + j] !== null) {
        pocket.push(this[i + j]);
      }
    }
    result.push([this[i]].concat(pocket));
  }

  if (arguments.length > 1) {
    return result.pockets.apply(result, [].slice.call(arguments, 1));
  }

  return result;
};

// Example of usage:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

arr.pockets(2); //=> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]]
arr.pockets(3); //=> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]

// Recursive:
arr.pockets(1, 3); //=> [ [[1], [2], [3]], [[4], [5], [6]], [[7], [8], [9]], [[10], [11]] ]

Answer №2

A simpler way to achieve this task is by utilizing the Array.slice method:

function groupItems(arr, chunkSize) {
    var result = [], index = 0, length = arr.length;
    while(index < length) {
        result.push(arr.slice(index, index + chunkSize));
        index += chunkSize;
    }
    return result;
}

This method is not only simpler but also more efficient. You can check out the performance comparison here: http://jsperf.com/groupItems

Answer №3

To achieve the underscore variant, you can utilize _.groupBy() and group by the index of the item:

var doubles = _.groupBy(singles, function (num, i) {
    return Math.floor(i / 2);
});

However, since _.groupBy() returns an Object, converting it to an Array requires some additional steps:

_.mixin({
    segment: function (coll, per) {
        var result = [];
        _.chain(coll)
            .groupBy(function (item, i) { return Math.floor(i / per)})
            .each(function (group, key) { result[key] = group; })
        return result;
    }
});

var singles = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];

var doubles = _.segment(singles, 2);
var triples = _.segment(singles, 3);

Answer №4

To achieve this in Python, one can use the zip(*[iter(xs)]*n) method. As a fun exercise, below is an implementation in JavaScript:

Let's begin with a basic generator function (until ES6 becomes more widely used):

StopIteration = {"name": "StopIteration"}

function iter(xs) {
    if('next' in xs)
        return xs;
    var i = 0;
    return {
        next: function() {
            if(i >= xs.length)
                throw StopIteration;
            return xs[i++];
        }
    }
}

next = function(it) { return it.next() }

The implementation of zip() is quite straightforward:

zip = function() {
    var args = [].map.call(arguments, iter), chunks = [];
    while(1) {
        try {
            chunks.push(args.map(next));
        } catch(StopIteration) {
            return chunks;
        }
    }
}

To create pairs that are linked, simply pass the same iter function twice to zip:

xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

it = iter(xs)
a = zip(it, it)

console.log(a)
// [[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]]

For creating N-pairs, an additional utility function is needed:

repeat = function(x, n) {
    for(var a = []; n; n--)
        a.push(x);
    return a;
}

a = zip.apply(this, repeat(iter(xs), 5))

console.log(a) 
// [[1,2,3,4,5],[6,7,8,9,10]]

It's important to note that like in Python, incomplete chunks are trimmed.

Answer №5

If you want to split an array into groups using reduce and Modulus (%), here's how you can achieve it:

const arrayGrouper = (arr, size) => arr.reduce((acc, val, i) => {
        i % size === 0 ?
            acc.push([val])
            :
            acc[acc.length - 1].push(val);
        return acc;
    }, []);

let groupedArray = arrayGrouper([10, 20, 30, 40, 50, 60], 3);

console.log(groupedArray);
//[[10, 20, 30], [40, 50, 60]]

For more information on JavaScript reduce, you can visit this link.

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

Limit the selection of 'pickable' attributes following selections in the picking function (TypeScript)

In the codebase I'm working on, I recently added a useful util function: const pick = <T extends object, P extends keyof T, R = Pick<T,P>>( obj: T, keys: P[] ): R => { if (!obj) return {} as R return keys.reduce((acc, key) => { re ...

Unable to manipulate the marker with the leaflet library

Currently, I am utilizing react.js with the leaflet library and would like to enable marker movement on the map when clicked, instead of adding a new one. Below is the code snippet I am working with: import React from "react"; import { MapConta ...

What is the best way to export a React Material-UI component with two separate styles objects in Material-UI V1?

We are currently utilizing material-ui version 1 and composing Higher Order Components (HOC) with the recompose utility. Our issue arises from having two separate styles objects - one defined within the component itself, and another general style object th ...

How can I implement a page switch in vuejs by clicking on a name in a table list?

I'm currently working on a list page in VueJS and facing some challenges. Here is the code snippet: <template> <vue-good-table :columns="columns" :rows="row" :search-options="{ ...

Is Asp.net 4 resetting the array with every new run?

I have developed a basic asp.net web page to generate HTML content. The concept is to store previous user inputs in an array each time they click a button, and display them along with the most recent input. However, I encountered an issue where the array a ...

An issue has been detected in the constants.json file located in the constants-browserify

I organized my folders into client-side and server-side categories, but I failed to work from a parent folder perspective. Now, as I attempt to deploy to Heroku, I realize that I need one main folder for the deployment process. To address this issue, I dec ...

Guide on executing a Python script using Node.js

I have set up a node.js server on Raspberry Pi and encountered an issue when trying to run a python script from it. Despite receiving the correct output from the client, the file fails to execute in this instance involving socket.io. The socket functiona ...

Tips on how to remove the first column from a jQuery hover effect

Currently, I have a function that enables hover events on a table. Right now, it excludes the header row but I also need it to exclude the first column. Any suggestions on how to do this? $(".GridViewStyle > tbody > tr:not(:has(table, th))") ...

Having trouble seeing the filtered results in the React Redux search filter?

I have implemented a search filter using react redux, but I am encountering an issue. When I type in text in the search field, the list of projects does not change according to the value I input into the search field. This should ideally filter the project ...

Enhancing my Javascript code by adjusting the styling of a link within the page navigation bar

Looking for assistance with a javascript and DOM code improvement. I currently have a page navigation bar structured like this (used on certain pages): <div id="pagebar"> <a href="iraq_pixra1.html">1</a> <a href="iraq_pixra2.html"> ...

Transform an array containing objects into a single object

Currently exploring the Mapael Jquery plugin, which requires an object to draw map elements. In my PHP code, I am returning a JSON-encoded array of objects: [ { "Aveiro": { "latitude": 40.6443, "longitude": -8.6455, ...

What could be causing appendChild to malfunction?

I'm having an issue trying to create three elements (parent and one child) where the third element, an <a> tag, is not appending to modalChild even though it's being created correctly. modal = document.createElem ...

Transform ISO-8859-1 encoding into UTF-8

Recently, I encountered an issue while sending a HTTP request using jQuery's ajax. The server, unfortunately, returns the response in ISO-8859-1 format while my page is set to UTF-8. This discrepancy causes some characters to become unreadable. How ...

How can PHP be used to iterate through numbers and retrieve letters?

Looking to start at a specific point in the alphabet and iterate through while skipping characters? I attempted this with the loop below, but now I'm wondering - how can I increase the starting point by 3 characters? $start = 'G'; for ($i = ...

Error: Unable to locate module '@emotion/react' in 'E:frontend ode_modules@muistyled-engine' directory

I've been trying to import a box component from @mui/material/Box. After installing Material-UI 5 using npm i @mui/material, I encountered the error message Module not found: Can't resolve '@emotion/react' in 'E:\frontend&bsol ...

"Adding an Image within a Textbox Using Ext JS: A Step-by-Step

How can I add a search image inside a textbox created with the following code? I have created a table with a footer, and within one of the textboxes in the table, I want to include a search button that will call another function when clicked. However, desp ...

Adjusting Headers Using Buttons

Having some issues with my JavaScript code. I'm trying to achieve a specific functionality where clicking the "Modify HTML content" button changes the h1 heading from "The Original Content" to "The New Content", and vice versa on subsequent clicks. Si ...

"Using a PHP array with Highcharts for dynamic data visualization

I am having difficulty inserting values into the array at specific positions. I want to create an empty array, retrieve data from the database, and based on whether they are global or local, populate the PHP array as shown below. However, I'm facing c ...

Hear and register keypress in Angular service

I offer a dialog service Check it out below @Injectable() export class HomeDialogService { public constructor(private readonly dialogService: DialogService, private readonly userAgent: UserAgentService) {} @HostListener('document:keydown.escape ...

Intersection observer automatically removes images from carousel (Siema) after they have been viewed

Check out this example to see the issue I'm facing. I've implemented an intersection observer for lazy loading images, here's the code: const pictures = document.querySelectorAll("[data-src]"); function loadPicture(pic){ const src = p ...