Aggregate information from an array containing multiple nested arrays

With regards to marking this as answered by another question, please take note that this is not a flat array but an array of arrays. Additionally, the numbers provided are just examples for visual representation.

I am attempting to iterate through an array of arrays with the following structure:-

[
   [1, 2, 3, 4, 5, 6, 7, 8, 9],
   [1, 2, 3, 4, 5, 6, 7, 8, 9],
   [1, 2, 3, 4, 5, 6, 7, 8, 9],
   [3, 2, 1, 6, 5, 4, 9, 8, 7],
   [6, 5, 4, 9, 8, 7, 3, 2, 1],
   [7, 8, 9, 3, 2, 1, 6, 5, 4]
]

How can I transform this array into chunks of 3x3 like so:-

[
   [1, 2, 3, 1, 2, 3, 1, 2, 3],
   [4, 5, 6, 4, 5, 6, 4, 5, 6],
   [7, 8, 9, 7, 8, 9, 7, 8, 9],
   [3, 2, 1, 6, 5, 4, 9, 8, 7],
   [6, 5, 4, 9, 8, 7, 3, 2, 1],
   [7, 8, 9, 3, 2, 1, 6, 5, 4],
]

I have chunked the array using the first 3 values from each sub-array, followed by the next 3 values, and then the final 3 values.

The resulting chunked array should appear as follows:-

1 2 3 | 4 5 6 | 7 8 9
1 2 3 | 4 5 6 | 7 8 9
1 2 3 | 4 5 6 | 7 8 9
---------------------
3 2 1 | 6 5 4 | 9 8 7
6 5 4 | 9 8 7 | 3 2 1
7 8 9 | 3 2 1 | 6 5 4

I have attempted iterating through each row, resetting the column count upon reaching an increment, and increasing the row number accordingly, but this approach was not successful.

I am willing to provide details of my previous attempts if it would be beneficial. Additionally, it's worth noting that the size of the array may vary but will always be divisible by a specific number, which in this instance is 3.

Further information has been added to the question. The array of arrays will consistently be divisible by a particular numerical value, with the current example demonstrating a divisibility by 3.

Answer №1

To tackle this issue, one can utilize a chunk method as discussed in Split array into chunks, along with a zip function similar to Python's as covered in

/** @see: https://stackoverflow.com/questions/8495687/split-array-into-chunks */
function divideArray(array, chunk) {
    let result = [];
    for (let i = 0; i < array.length; i += chunk) {
        result.push(array.slice(i, i + chunk));
    }
    return result;
}

/** @see: https://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function */
function zip(...rows) {
    return [...rows[0]].map((_, c) => rows.map((row) => row[c]));
}

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

const result = divideArray(array, 3)
    .flatMap((innerChunk) =>
        zip(...innerChunk.map((arr) => divideArray(arr, 3)))
        .map((arr) => arr.flat())
    );

console.log(result.map((a) => a.join(', ')));

// Reverses the operation to get back to the original
const reversed = divideArray(result, 3)
    .flatMap((innerChunk) =>
        zip(...innerChunk.map((arr) => divideArray(arr, 3)))
        .map((arr) => arr.flat())
    );

console.log(reversed.map((a) => a.join(', ')));

Answer №2

If you want to achieve this, you can utilize a nested loop and slice the array based on the size of the outer array each time.

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

let out = [];
for(let i in arr) { out.push([]);}

arr.forEach((e, i) => {
    let scale = e.length / arr.length;
    for(let j in arr)
    {
      out[j] = out[j].concat(e.slice(j * scale, j * scale + scale));
    }
});

console.log(out);

Here is the code snippet with the original array before your changes:

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

let out = [];
for(let i in arr) { out.push([]);}

arr.forEach((e, i) => {
    let scale = e.length / arr.length;
    for(let j in arr)
    {
      out[j] = out[j].concat(e.slice(j * scale, j * scale + scale));
    }
});

console.log(out);

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

Choose an element from within a variable that holds HTML code

I have a specific div element that I need to select and transfer to a new HTML file in order to convert it into a PDF. The issue I'm facing is related to using AJAX in my code, which includes various tabs as part of a management system. Just to prov ...

Tips for using Jquery to round up currency values

Is there a way to round up various currencies using jQuery? I have a specific requirement: 10.30 → 10 //Round down if below .5 10.60 → 11 //Round up if after .5 849.95 → 850 1,022.20 → 1022 ...

Error: OpenAI's transcription API has encountered a bad request issue

const FormData = require('form-data'); const data = new FormData(); console.log('buffer: ', buffer); console.log('typeof buffer: ', typeof buffer); const filename = new Date().getTime().toString() + '.w ...

How can you optimize the storage of keys in JS objects?

Just pondering over this scenario: Consider a line definition like the one below, where start and end are both points. let ln = { s: {x:0, y:0}, e: {x:0, y:0}, o: 'vertical' } Now imagine having a vast array of lines, how can we sav ...

Downloading PDF files on IOS while using Angular often results in the PDF opening in the same

I'm currently utilizing file-saver within my Angular application to retrieve a PDF generated from the backend. The library functions smoothly on desktop and Android devices, but I'm encountering issues with downloading files on iOS. Contrary to w ...

"Experiencing a problem with Next.js 13 where the User Context is not functioning properly outside of _app

When using Next.js 13 and the user context, I've noticed that it doesn't function properly outside of _app.tsx. Any idea why? src>context>UserPositionContext.tsx import { createContext, useContext, useState } from "react"; const ...

Is it necessary for Webpack to process the index.html file for Vue applications?

I am facing an issue with my index.html file where the assets inside the head tag are not loading as images but as the index.html file itself. I have included the following links in my head tag: <link rel="apple-touch-icon" sizes="60x60" href="./assets ...

Creating multiple objects in a threejs instance with varying sizes and positions

Recently, I decided to try out the InstancedBufferGeometry method in order to improve performance when rendering thousands of objects. Specifically, I wanted to create instances of cube geometries with varying heights. AFRAME.registerComponent('insta ...

Need help with writing code in Angular for setting intervals and clearing intervals?

I am working on the functionality to display a loader gif and data accordingly in Angular. I have tried using plain JavaScript setInterval code but it doesn't work for $scope.showLoader=true and $scope.showResult=true. The console.log('found the ...

What is preventing me from accessing my session array in this.state.props from my mapStateToProps in React-Native Redux?

I am currently facing an issue with my Redux store setup. I am attempting to store an array of Session objects, where each Session object contains an array of Hand objects. However, when trying to access my store using `mapStateToProps`, none of the option ...

Utilizing Kendo MVVM to Bind to an Self-Executing Anonymous Module Function

Currently, I am experimenting with the Kendo UI MVVM framework and attempting to bind it to a self-executing anonymous modular function. The situation is a bit complex, as the functionality is only somewhat working. Although the module is being updated whe ...

Modifying the default error message in Yup: A step-by-step guide

What is the process for modifying the default error message to a custom error message? Specifically, my custom message. const VALIDATION_SCHEME = Yup.object().shape({ numOne: Yup.Number().required('!'), numTwo: Yup.Number() .r ...

The addition of days is producing an incorrect result

When extracting the date from FullCalendar and attempting to edit it, I noticed that moment.js seems to overwrite all previously saved dates. Here is an example of what's happening: var date_start = $calendar.fullCalendar('getView').start.t ...

Update the navigation bar from displaying "LOGIN" to "LOGOUT

I am facing a challenge in updating the navbar login link to a logout link once the user logs in. I have attempted the following: header.ejs: <ul class="nav navbar-nav navbar-right"> <li id="home"><a href="/ ...

To restore the position of the chosen object in Three.js after clicking reset

I am facing an issue with resetting the position of my latest Object in three.js. Initially, my code consists of the following: function onDocumentMouseDown( event ) { event.preventDefault(); var vector = new THREE.Vector3( mouse ...

What is the most efficient way to iterate through an array to push properties into an object nested within another array?

I have been working on a small Angular application that functions as a scheduler, allowing users to input a Name, Start and End dates, and toggle a boolean checkbox through a form. One challenge I am facing is trying to assign the names entered by each use ...

Automatically increase the height of a text area as you type beyond the maximum width limit

Is there a way to dynamically expand the textarea width as I type beyond its maximum set width without displaying a horizontal scrollbar? Here is the HTML code in its rendered form: <textarea name="CatchPhrase" class="inp ...

The functionality of the Vue.js single file component is not performing as anticipated

Recently, I've been experimenting with Vue and Vue CLI. I came across this amazing vue-tabs-component that I would like to try out. Here is a snippet of my code from App.vue: <template> <div> <tabs> <tab name="Fir ...

Implementing inline styles in the HEAD section of a Next.js website

I currently have a blog hosted on Jekyll at , and I'm looking to migrate it to Next.js. My unique approach involves embedding all the styles directly into the HEAD element of each HTML page, without utilizing any external stylesheet files. However, wh ...

Want to achieve success with your AJAX calls in JavaScript? Consider using $.get

As I clean up my JavaScript code, I am looking to switch from using $.ajax to $.get with a success function. function getresults(){ var reqid = getUrlVars()["id"]; console.log(reqid); $.ajax({ type: "POST", url: "/api/ser/id/", ...