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.
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.
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]] ]
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
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);
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.
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.
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 ...
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 ...
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 ...
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="{ ...
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 ...
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 ...
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 ...
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))") ...
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 ...
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"> ...
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, ...
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 ...
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 ...
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 = ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...