Vertical sorting of arrays in JavaScript based on index positions

Here is an array containing the letters of the alphabet: ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]

From the server, I receive the number of columns to display. Let's assume it's 3 for this example.

I have a function that works well, except when my index matches the array length. In that case, the order gets mixed up and I am unsure how to resolve it.

var i;
var j;
var columns = window.columns; // Assuming 3 for this example.
var lettersArray= ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var rows = Math.ceil(lettersArray.length/columns);

Current progress:

 for (i = 0; i < rows; i++)
            {
                     for (j=0; j < lettersArray.length; j=j+rows)  
                     {

                        var index = i+j;
                        if (index>=lettersArray.length)
                        {
                            break;
                        }
                        else
                        {
                          PrintArray(lettersArray, index); 
                        }   
                     }
            }

The PrintArray function takes the index and the array post-sorting, producing the expected result:

A J S 
B K T 
C L U 
D M V
E N W
F O X
G P Y 
H Q Z 
I R

However, during execution, the output strays from the intended format:

A J S 
B K T 
C L U 
D M V
I N W
F O X
G P Y 
H Q R 
E Z

Answer №1

So basically, what you're suggesting is to loop through each element using the formula row + col * rows. It's crucial to keep iterating even if you encounter undefined elements as there might be more rows to process.

Let me demonstrate how this can be accomplished:

function iterateData(data, cols) {
    var rows = Math.ceil(data.length / cols);
    var col, row;
    for (row = 0; row < rows; ++row)
        for (col = 0; col < cols; ++col)
            console.log(data[row + col * rows] || '');
}

In this code snippet, console.log is used to print out the next element in the sequence or an empty string if the element is undefined.

Answer №2

Check out this effective approach that involves utilizing genuine sorting techniques.

var letters = [];
var start = 'A'.charCodeAt(0);
var end = 'Z'.charCodeAt(0);
for (; start <= end; start++)
  letters.push(String.fromCharCode(start));

function findLetterIndex(char) {
  return char.charCodeAt(0) - 'A'.charCodeAt(0);
}

var gridCols = 3; // Also known as numCols; Fetched from the server.
var gridRows = Math.ceil(letters.length / gridCols);
function generateKey(char) {
  return (gridCols * (findLetterIndex(char) % gridRows)) +
         Math.floor(findLetterIndex(char) / gridRows);
}

letters.sort(function(alpha, beta) {
  return generateKey(alpha) - generateKey(beta);
});

for (start = 0, end = letters.length; start < end; start += gridCols)
  console.log(letters.slice(start, start + gridCols).join(' '));

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

Sorting an array of floating point numbers in Java: How to arrange them in descending order?

When attempting to sort an array of floats in reverse order using the following code snippet, I encountered an error message. Can you help me identify the issue? float sortedData[]=new float[100]; ... Arrays.sort(sortedData,Collections.reverseOrder()); ...

Create a customized multibar chart in Angular using NVD3 that displays only a line graph on the dual y-axis, visualizing

Currently, I am experimenting with developing an angular multibarchart that features only lines, with no bars. Instead of using Lee Byron's test data generator, I am keen on generating data using JSON. However, I am faced with the challenge of convert ...

interval-based animation

I'm trying to create a simple animation using setInterval in JavaScript. The goal is to make an image move from left to right. HTML: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"& ...

Module exists; however, command could not be located

I am experiencing an issue with the rimraf node module. Despite being able to access its folder within the node_modules directory, I am receiving errors indicating that the command for rimraf cannot be found. I have attempted to delete the entire node_mod ...

Firestore - Safely removing a large number of documents without running into concurrency problems

I've encountered issues with my scheduled cloud function for deleting rooms in a Firestore-based game that were either created 5 minutes ago and are not full, or have finished. Here's the code I'm using: async function deleteExpiredRooms() ...

When using TouchableWithoutFeedback, I encountered the following error message: "Error: React.Children.only expected to receive a single React element child."

I am encountering the following issue: Error: React.Children.only expected to receive a single React element child. Whenever I incorporate the 'TouchableWithoutFeedback' component in my ReactNative project: return ( <TouchableWithoutFeed ...

Using JSON Array List Values to assign variables

I have successfully obtained the JSON ArrayList and utilized RecyclerView to display the data. This is how I am displaying the JSON array using RecyclerView : public void onResponse(Call<List<Fame>> call, Response<List<Fame>> resp ...

Ways to capture targeted requests

Utilizing NestJS and Angular 2, I have noticed that both frameworks have a similar approach when it comes to working with Interceptors. I am currently looking for the best practice to identify specific requests in order to perform additional tasks. When d ...

Display dynamic content with AJAX in a pop-up modal window while also updating the

Currently, when I click on a button, a modal pops up with data retrieved from an ajax action that has been given an id. I would like the URL to update when this happens. Additionally, I want the option for the modal to preload if someone directly accesses ...

Sending JSON Data over URL

I am facing a challenge with passing data between two HTML files. My initial solution involved sending the data through the URL using the hash and then parsing the link using JSON.parse(window.location.hash.slice(1));. This method worked for a few attempts ...

Issue in Next.js 13: Byte index exceeds limits when running 'npm run dev' command

When attempting to install Next.js 13.4.12, I utilized the command npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385b4a5d594c5d15565d404c1559484878090b160c1609">[email protected]</a>. The installation process ...

Prevent user scrolling when full-screen menu is activated

Currently, I am developing a full-screen menu for a website and facing an issue with disabling the user's ability to scroll when the menu is open. Despite searching online, I have not found a suitable solution. It would be greatly appreciated if someo ...

What are the steps for conducting a component test with material ui?

My current component is built using . import React from 'react'; import { AppBar, Toolbar } from 'material-ui'; import { Typography } from 'material-ui'; import { MuiThemeProvider, createMuiTheme } from 'material-ui/sty ...

Are you unsure whether to use Ajax or jQuery? If you need assistance in adding parameters to

Currently delving into ajax/jQuery and encountering some hiccups. Here's the code snippet: .click(function() { var period = 'ALL'; if ($('#registerat input:checked').val() != 'ALL') period = ...

Converting a buffer to a string in Python 3, similar to Node.js 6.0.0

I am currently in the process of translating an old node.js library into Python and I am facing difficulties trying to replicate the behavior of Buffer.toString() in Python. The library is used in a node 6.0.0 environment. While researching, I came acros ...

Displaying Values/Marks in a Unique Order with Material-UI Slider Component

The default behavior of the Material-UI slider is to display marks/values in ascending order from min to max For instance, if you have a slider configured like this: const marks = [ { value: 1, label: '1' }, { value: 2, lab ...

The login page allows entry of any password

I'm running a xamp-based webserver with an attendance system installed. I have 10 registered users who are supposed to log in individually to enter their attendance. However, there seems to be an issue on the login page where any password is accepted ...

Customize Bootstrap layout on the fly

I have encountered a slight dilemma. I am attempting to implement something similar to the following: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com ...

Shifting v-slot references into a Vue.js component - tips and tricks!

I'm struggling to understand how to transfer the v-slot data into a component. Suppose I want to restructure the code below: <template v-slot:item="data"> <template v-if="typeof data.item !== 'object'"> <v-list-item-co ...

The error message that appeared states: "TypeError Object[object object] does not have the SubSelf method, TypeError Object[object object] does not

As I delved into a WebGL project, leveraging the powerful Sim.js and Three.js libraries, an unexpected obstacle emerged: At a certain point, within the code, the constructor for THREE.Ray is utilized in this manner: var ray = new THREE.Ray( this.camera.p ...