The unexpected actions while altering the direction of iteration in a 2D array and sorting elements

If we consider a 2D array:

┌─────────┬───┬───┬───┐
│ (index) │ 0 │ 1 │ 2 │
├─────────┼───┼───┼───┤
│    0    │ 2 │ 3 │ 2 │
│    1    │ 3 │ 1 │ 3 │
│    2    │ 2 │ 2 │ 3 │
└─────────┴───┴───┴───┘

The goal is to sort the elements in this 2D array and arrange them in a line from top to bottom as shown below:

┌─────────┬───┬───┬───┐
│ (index) │ 0 │ 1 │ 2 │
├─────────┼───┼───┼───┤
│    0    │ 1 │ 2 │ 3 │
│    1    │ 2 │ 2 │ 3 │
│    2    │ 2 │ 3 │ 3 │
└─────────┴───┴───┴───┘

Currently, there is code available for this process:

const generateArray = (size, min, max) =>
    Array(size)
    .fill(0)
    .map(() => generateNumber(min, max));

const generateArray2D = (rows, cols, min, max) =>
    Array(rows)
    .fill(0)
    .map(() => generateArray(cols, min, max));

const generateNumber = (min, max) =>
    Math.floor(Math.random() * (max - min + 1)) + Math.floor(min);

const generated2DArray = generateArray2D(
    rows,
    cols,
    10,
    30
);

const sortedArray = [...generated2DArray].flat(1).sort(((a, b) => a - b))

for (const sortedElement of sortedArray) {
  for (let j = 0; j < generated2DArray.length; j++) {
    for (let i = 0; i < generated2DArray[j].length; i++) {
      generated2DArray[i][j] = sortedElement;
    }
  }
}

However, each field in the resulting array contains only the last element from the sorted sortedArray like so:

┌─────────┬────┬────┬────┬────┬────┐
│ (index) │ 0  │ 1  │ 2  │ 3  │ 4  │
├─────────┼────┼────┼────┼────┼────┤
│    0    │ 30 │ 30 │ 30 │ 30 │ 30 │
│    1    │ 30 │ 30 │ 30 │ 30 │ 30 │
│    2    │ 30 │ 30 │ 30 │ 30 │ 30 │
│    3    │ 30 │ 30 │ 30 │ 30 │ 30 │
│    4    │ 30 │ 30 │ 30 │ 30 │ 30 │
└─────────┴────┴────┴────┴────┴────┘

Several attempts were made to resolve this issue without success. Any suggestions on how to address this problem would be greatly appreciated.

Answer №1

During each iteration of the outer loop, the inner loops assign all elements in the result array to sortedArray[0] on the first cycle, sortedArray[1] on the second cycle, and so forth. This results in the entire generated2DArray being filled with the same value on each pass through the outer loop.

To avoid using the outer loop, you can directly loop through the indexes in the 2D array and increment the index in the 1D array without nested looping structures.

k = 0;
for (let j = 0; j < generated2DArray.length; j++) {
    for (let i = 0; i < generated2DArray[j].length; i++) {
        generated2DArray[i][j] = sortedArray[k++];
    }
}

Answer №2

The issue arises from the fact that you are iterating through the entire grid for each element in your flattened and sorted array.

To address this problem, consider eliminating the outer loop and determining the position within the two-dimensional array using the following method:

for (let j = 0; j < generated2DArray.length; j++) {
    for (let i = 0; i < generated2DArray[j].length; i++) {
        generated2DArray[i][j] = sortedArray[i*generated2DArray.length+j];
    }
}

Answer №3

To efficiently rearrange the elements in a 2D array, you can first generate an array of random numbers and then sort it to create a sorted array. By calculating the row and column index based on the element's position in the sorted array, you can update the values in the output array accordingly.

const generateArray = (size, min, max) =>
  Array(size)
  .fill(0)
  .map(() => generateNumber(min, max));

const generateArray2D = (rows, cols, min, max) =>
  Array(rows)
  .fill(0)
  .map(() => generateArray(cols, min, max));

const generateNumber = (min, max) =>
  Math.floor(Math.random() * (max - min + 1)) + Math.floor(min);

const rows = 3
const cols = 4

const generated2DArray = generateArray2D(rows, cols, 10, 30);
const sortedArray = [...generated2DArray].flat(1).sort(((a, b) => a - b))

for (let i in sortedArray) {
  const col = Math.floor(i / rows)
  const row = i - (col * rows)

  generated2DArray[row][col] = sortedArray[i]
}

for (let a of generated2DArray) {
  console.log(JSON.stringify(a))
}

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

Array of initials for full names in JavaScript

const nameList = ['John Doe', 'Jack Lock', 'Nick Load']; const initials = nameList.map([n]) => n); console.log(initials); I'm attempting to display the initials of the array items, but I'm only able to retrieve t ...

Retrieving JSON information from a nested array

I've noticed that this question has been asked frequently, but I haven't come across a case similar to mine. Here's the array printed out from a JSON response: Array ( [contents] => { "type": "XXXXXXXXXXXXXXX", "previous": " ...

When utilizing AngularJS, a parse error is triggered by array[ {{value}} ], but I prefer to overlook it

Within the controller, I have a selection list that is displayed like this: <select class="input form-control" id="animationTime" ng-options="item as item.label for item in aniCon.timeOptions track by item.id" ng-model="aniCon.popupTime" ...

The parent node is returning a child element

Currently working on a website using Vue 3.0 and Element+ and encountering an inconsistency. There is a div displayed on the page (an array of objects) and the goal is to remove the object from the array when a button is clicked. The issue arises when som ...

Sorting arrays can yield varying results depending on the browser being used

The variations in output between Chrome 70.0, Chrome 69.0, and Firefox 63.0 for the same code are puzzling. var arr = [1,2,43,1233,5546,33,6,11]; arr.sort(() => -1); //[11, 6, 33, 5546, 1233, 43, 2, 1] arr.sort(() => 1); //[1, 2, 43, 1233, 5546, 33, ...

chart for visualizing two rows with matching IDs and dates

I have been attempting to accomplish the following two scenarios: 1) When both ID and dates are the same in the chart, but the descriptions differ, I want to display them on separate lines. 2) If there is not enough room to show the row label, I would li ...

Having difficulty establishing a connection between my node.js application and the database

I've been struggling to establish a connection between my application and the database. Despite attempting the code below, my models are still not being recognized. const MongoClient = require('mongodb').MongoClient; const assert = require(& ...

Is it possible to modify the dirpagination filter in AngularJS from an input box to a select box?

I have been experimenting with the AngularJS dirpagination library. Feel free to check it out at this link. You can also see a code demo at: this link. My question is, is it possible to change the input box to a select box and still have the same functio ...

The three.js library is throwing an error because it is unable to access the 'geometry' property of an

function CreateNewSphere(x, z) { var sphereGeometry = new THREE.SphereBufferGeometry(10 * factor, 32, 32); var sphereMaterial = new THREE.MeshBasicMaterial({ color: SphereColor, wireframe: false }); var sphere = new THRE ...

Display only certain links using CSS or JavaScript/jQuery within a widget that appears once the webpage is fully loaded

I'm currently facing an issue on a website that requires a solution involving jQuery/javascript, which I am not proficient in. After the page loads, javascript is executed which renders various html/css elements. The specific portion we are focusing ...

Fetching images using node.js via URL

I must apologize for my lack of knowledge about node.js. I am trying to read an image from a URL and resize it using sharp. Currently, my code only works for reading local images. For instance, I would like to read the following image from a URL: url= ...

Sequencing and fulfillment of promises in a job queue using Promise.race

Currently, I'm grappling with the concepts of job queue and promise resolution in Javascript. While going through Nicholas Zakas' book "Understanding ECMAScript 6", I came across a code snippet regarding Promise.race() that has left me puzzled: ...

Having difficulty animating camera rotation in ThreeJS with Tween

I am facing an issue with animating the ThreeJS camera rotation using TweenJS. While I can successfully tween the camera position, the camera.rotation does not seem to update as expected. To illustrate my problem, I have created a simple example based on ...

EC2 experiencing issues with Node cron execution

My setup involves running python and node scripts as cron jobs on EC2. Interestingly, the python scripts are executing without any issues, but the node scripts seem to be failing. When I manually activate the node scripts from the command line, they work p ...

Unable to find '/images/img-2.jpg' in the directory 'E:React eact-demosrc'

My code is giving me trouble when trying to add an image background-image: url('/images/img-2.jpg'); An error occurred during compilation. ./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src?? ...

Troubleshooting a C++ array assignment issue: What mistake did I make in my code?

I'm encountering an issue with this code snippet in CodeBlocks as it's returning random numbers instead of the expected multipliers of 25. Can someone please review the code and point out my mistake? Here's the code: #include <iostream> ...

Error on page refresh: Unable to access properties of null while attempting to read 'addEventListener'

Having a couple of HTML pages where I load code snippets using jQuery's .load method. Here is an example from my index.html: $('#rotating-content').load(`./snippets/shared/rotating-content.html`); The "rotating-content.html" contains two Bo ...

When utilizing PassportJS, SequelizeJS, and JWT tokens, req.user may be found to be undefined

Despite searching various answers on Stackoverflow and consulting the documentation, I am still unable to identify what might be causing the issue. Within my application, I am utilizing SequelizeJS to interact with my MySQL database and now attempting to s ...

Learn how to insert JavaScript code into the head of an iframe using jQuery

My goal is to inject javascript code into the head of an iframe using jquery with the code provided below. var snippets_js='<?php echo $snippets_javascript;?>'; var scriptjs = document.createElement("script"); scriptjs.type = "text/j ...

communication flow in two directions between server and client

Looking for recommendations on a javascript/nodejs solution that enables bi-directional communication between server and client. The application flow involves the client sending a discovery service to the server, which responds with a challenge. The client ...