Divide a given number of elements within an array of arrays

Presented below is an array:

[
  {
    "id": "34285952",
    "labs": [
      {
        "id": "13399-17",
        "location": "Gambia",
        "edge": ["5062-4058-8562-2942-2107-2064-58"]
      }
    ]
  },
  {
    "id": "85130775",
    "labs": [
      {
        "id": "52504-72",
        "location": "Nepal",
        "edge": [
          "5232-9427-8339-7218-3936-9389-52",
          "6375-9293-7064-5043-6869-4773-65",
          "8547-4739-6334-3896-7208-8243-67"
        ]
      }
    ]
  },
  {
    "id": "67817268",
    "labs": [
      {
        "id": "17891-68",
        "location": "U.S.",
        "edge": [
          "6383-7536-7257-4713-9494-9910-93",
          "6743-8803-1251-1173-5133-2107-19"
        ]
      }
    ]
  },
  .... other objects may exist but are omitted for brevity
]

Create a function that accepts a number as input. This function should then group the objects in the array based on this number, such as grouping ten objects into Arrays of Array.

If there are 22 objects in the array, the output should consist of three arrays within the main array.

For instance:

Input:

[ { }, { }, { }, { }, { }, { }, { }, { }, ]

Output (grouped by two):

[ [ { }, { } ], [ { }, { } ], [ { }, { } ], [ { }, { } ] ]

An initial approach could involve counting the objects and then merging them accordingly:

// array = see above example
// countOption = 10

const splitArrayByCount = (array, countOption) => {
  return array.map(object => {
    if (array.length > countOption) {
      return [object]
    }
  })
};

This concept can be useful for pagination purposes.

Answer №1

Get the number of arrays by using

Math.ceil(array.length/countOption)
. Then append a slice of the original array to the result.

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
const countOption= 10
let result = []

for (let i = 0; i < Math.ceil(array.length / countOption); i++) {
  result.push(array.slice(i * countOption, (i + 1) * countOption))
}
console.log(result)

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

The functionality of TypeScript's instanceof operator may fail when the method argument is not a simple object

There seems to be an issue with a method that is being called from two different places but returns false for both argument types. Despite checking for the correct types, the problem persists and I am unsure why. Although I have read a similar question on ...

Refresh database post drag and drop operation

I am seeking a way to update a "state" SQL row after dragging an element between the "DZ", "WT", and "ZK" divs. Below is a snippet of my code: SQL queries: $sql = "select * from tasks where login = '$user_check' AND state = 1"; $sqlDodane = mys ...

Defeat the all-powerful !important tag and enable dialog customization for positioning

I am currently developing a browser extension and I am encountering an issue with using JQueryUI to display a modal dialog. The problem arises when certain websites, for example espn.com, also utilize JQueryUI but do not properly scope their own elements. ...

I'm puzzled as to why my Vuex modules are not functioning properly. I keep receiving the error message: "[vuex]

I've been searching for hours and can't figure out why I keep getting this error message: [vuex] unknown mutation type: groceryStore/getStoreApple on all of the commits to the mutations in the groceryStore-module. I believe I'm following the ...

Is there a way to customize the hover style of Material UI Select or Menu MenuItem using the theme?

The theme I designed import { createMuiTheme } from 'material-ui/styles'; export const MyTheme = createMuiTheme({ palette: { primary: { light: '#757ce8', main: '#3f50 ...

Is there a way to use lodash to convert an array into an object?

Below is an array that I am working with: const arr = [ 'type=A', 'day=45' ]; const trans = { 'type': 'A', 'day': 45 } I would appreciate it if you could suggest the simplest and most efficient method to ...

Iterating through elements within a Div will retrieve the initial element exclusively

Is there a way to loop through all elements within the MainDiv Div in order to retrieve their values? Currently, I am only able to retrieve the value of the first element. <div id="MainDiv"> <input type="text" id="MyText"value="Text1" /> ...

What is the process for executing a Js file on a website?

I am looking to automate some tasks on a website that I do not own. Specifically, I need to automatically fill out a form and perform certain clicking actions. Can JavaScript be used for this purpose? I am unsure how to run a .js file on a site without the ...

Creating dynamic checkboxes in Angular4 and binding them to an array of IDs

Hey there developers, I've been encountering an issue while trying to bind my dynamically generated checkboxes to an array in my project. In my users.template.html file, I have the following code snippet: <div *ngFor="let r of roles" class="checkb ...

The Typescript module in question does not contain any exported components or functions related to

I've encountered an unusual issue while working on a React, Redux TypeScript application. It seems that after making some changes, one of the modules has stopped exporting its members. Here is the folder structure: src |---- components |---- contain ...

Creating a universal wrapper function to serve as a logging tool?

Currently, I am working on a generic JS function that can wrap any other function. The purpose of this wrapper is to execute the wrapped function, log the input and output events, and then return the output for "transparent" logging. However, as I attempt ...

A declaration file for the 'vuelidate' module could not be located

When I was following the installation instructions for Vuelidate in Vuejs (), I encountered a warning message at this line: import Vuelidate from 'vuelidate' The warning states: There seems to be an issue with finding a declaration file for t ...

Unable to Pause Video with Javascript

I have a project with a video that plays in a continuous loop. Below is the HTML code for the video tag: <video playsinline autoplay muted loop id="myVid"> <source src="River.mp4" type="video/mp4"> </video> My goal is to make the vi ...

Implement the addition of a class upon hovering using AngularJS

My goal is to include a new class when hovering over the li element using Angular in the code snippet below. <li ng-mouseenter="cola-selected=true" class="pull-left" ng-class="{'selected' : cola-selected}"> <a href="interna.html"> ...

The mysterious case of jQuery DOM alterations vanishing from sight in the view

I have a quick inquiry. I've been exploring jQuery lately and discovered the ability to dynamically add HTML elements to the DOM using code like $('').append('<p>Test</p>'); However, what surprised me is that these ap ...

Angular doesn't support this particular type as an injection token

I'm attempting to create a constructor with a type of string, but I keep encountering the following error: This particular type is not supported as an injection token @Injectable({providedIn: 'root'}) export class DataService { const ...

Instructions for adding a Key every time a user clicks the space Key within an Input field

I built a Movie Search Page with the OMDB API. My current issue is that the API returns an error when searching for a movie with more than one word because the API URL requires a + key between each word. I am looking for a way to automatically add the + ke ...

I'm seeking some assistance in resolving my JavaScript issue

Let's create a function known as 'bigOrSmall' that requires one parameter, 'arr', which will contain an array of numbers. Inside the 'bigOrSmall' function, let's define a new array named 'answers'. Next, it ...

Accessing an Excel file in TypeScript using the .xlsx format

After extensive research, I managed to find a solution for reading the .xlsx file in a TypeScript environment. Once implemented, I documented the solution along with a question and answer. The file "demo.xlsx" contains UserIds and Code, displayed in the i ...

Exploring the functionality of URLs in Node.js

I am working on testing an array of URLs to ensure that each one returns a 200 response code. So far, I have written the following code to accomplish this task. However, I have encountered an issue where only the last URL in the array is being tested. How ...