Shuffle not JavaScript array!

After extracting data from PDF files, I found myself with a vast array of information. Each PDF page contained 10 data items arranged in two columns, causing the data to be shuffled. While the first and last items were correctly positioned within each group of ten, the rest were mixed up.

Currently, the order of the data is 0, 2, 4, 6, 8, 1, 3, 5, 7, 9, 10, 12, 14, 16, 18, 11... but I require it to be in sequential order starting from 0, 1, 2, 3...

I have attempted to iterate through the array and transfer items into a new array using various if statements, yet I seem unable to achieve the desired outcome.

Answer №1

Presented below is a function designed to handle incoming data along with two additional parameters specifying the number of columns and rows on a page:

function uncolumnize(data, numColumns, numRows) {
    let perPage = numColumns * numRows;
    return data.map((_, i) =>
        data[Math.floor(i / perPage) * perPage 
           + Math.floor((i % perPage) / numColumns) 
           + (i % numColumns) * numRows]
    );
}

let result = uncolumnize([0,2,4,6,8,1,3,5,7,9,10,12,14,16,18,11,13,15,17,19], 2, 5);
console.log(result);

This implementation utilizes the map Array method as the resulting array will have the same length as the original data. The callback specified for map only relies on the index rather than the value itself. This index assists in determining the page, row, and column information. By rearranging the row and column values, a new index is constructed which then retrieves the corresponding data.

Answer №2

10 elements in 2 columns per page will be grouped as

10n, 10n+2, 10n+4, 10n+6, 10n+8, 10n+1, 10n+3, 10n+5, 10n+7, 10n+9

There will be groups of 10 elements with the last group having 0-9 elements.

N = 5 //total rows
len = array.length //array contains numbers
groups_of_2n_len = len / (2 * N)
last_group_len = len % (2 * N)

//Process complete groups
for(group_i = 0; group_i < groups_of_2n_len; group_i = group_i + 1) {
    temp_array = array.slice(group_i * 2 * N, group_i * 2 * N + 2 * N)
    element = group_i * 2 * N

    for(temp_i = 0; temp_i < N; temp_i = temp_i + 1) {
        array[element] = temp_array[temp_i]
        array[element + 1] = temp_array[temp_i + N]
        element = element + 2
    }
}

//Handle last group
if(last_group_len == 0) return

temp_array = array.slice(groups_of_2n_len * 2 * N)

element = groups_of_2n_len * 2 * N

for(temp_i = 0; temp_i < Math.floor(last_group_len / 2); temp_i = temp_i + 1) {
    array[element] = temp_array[temp_i]
    array[element + 1] = temp_array[temp_i + Math.floor(last_group_len / 2) + last_group_len % 2]
    element = element + 2
}

Answer №3

https://www.w3schools.com/jsref/jsref_sort.asp

Highlighted example:

var nums = [6, 3, 8, 2, 5];
nums.sort(function(x, y) {
  return x - y;
});
console.log(nums);

// [2, 3, 5, 6, 8]

If you have numbers in two different arrays you can try this approach...

const arr1 = [10, 15, 20, 25, 30];
const arr2 = [35, 40, 45, 50, 55];
const merged = [...arr1, ...arr2];
console.log(merged);

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

Tips for changing the size and color of SVG images in a NextJS application

Looking to customize the color and size of an svg image named "headset.svg". Prior to this, I used next/image: <Image src={'/headset.svg'} alt='logo' width={30} height={30} className='object-contain' /> The s ...

I'm encountering an issue with Regex.test

When working with the following JavaScript code... $.post(url, data, function (json) { var patt = new RegExp('/^\[{"dID":/'); if (patt.test(json)) { //output json results formatted } else { //error so o ...

React frontend encountered a connectivity issue while trying to establish a network connection

Our app utilizes next.js connected to express, which is further linked to AWS MySql for database management. While attempting to load some products stored in the database, an error message pops up: TypeError: NetworkError when trying to fetch resource. ...

How can I send a variable to a service using AngularJS?

I am currently working on developing an app for movie tracking, and I am fairly new to Angular. I am facing a challenge in passing a variable to this service. Instead of hardcoding the URL, I want it to be a variable. What is the best approach to achieve ...

Sending data from an external input field to a form using AngularJS programmatically with element name

I am facing a challenge where I need to include an Input element in a Form, even though the Input is located outside of the form. While I have managed to add the input using form.$addControl(outerInput), it is not producing the desired outcome as shown in ...

Passport.js: Navigating Users in the Right

I've been working on integrating passport.js, passport-google-oauth, and nodjes to retrieve a user's profile locally. However, I'm facing an issue with the redirect after logging in. Although the information is successfully loaded (I can acc ...

Creating a JSON body using a JavaScript function

I am looking to generate a JSON Body similar to the one shown below, but using a JavaScript function. { "events": [{ "eventNameCode": { "codeValue": "xyz api call" }, "originator": { "associateID": "XYZ", "formattedName": " ...

Smoothly animate a Three.js object in response to an event without changing its current position

I need assistance with slowing down the rotation animation of a cube when a mouse hovers over it and making it continue smoothly on mouse leave. The current issue I'm facing is that when the mouse enters the cube, the rotation slows down but abruptly ...

The value is not being populated in the text area when the onchange event occurs

<textarea className="form-control queryheight box_xp" placeholder="Enter Dashboard Content" type="text" onChange={this.dashboardtextchartchange.bind(this)} value={this.state.textdashboard}> </textarea> Function triggered on change : dashb ...

Is it possible to request/scrape pages from the client side?

Let me present the issue at hand: I am currently managing a web application that serves as a notification system which updates frequently. This application is operational on several local computers, each of which solely display information without any inp ...

How can you eliminate the first elements of two or more arrays of objects until all of their first elements match based on a specific field?

My Typescript code includes a Map object called `stat_map` defined as const stat_map: Map<string, IMonthlyStat[]> = new Map(); The interface IMonthlyStat is structured as shown below (Note that there are more fields in reality) export interface IMon ...

Is there a way to verify if the current event marks the conclusion of the events transmitted to a webhook?

Currently, I am in the process of coding a Google Apps Script web app that will react to events from the Telegram API using a chat bot. The first step was setting up a webhook to collect these events through the Google webhook. Since logger.log is unavaila ...

Issue with Click event not working on dynamically added button in Angular 8

My goal is to dynamically add and remove product images when a user clicks the add or delete button on the screen. However, I am encountering an issue where the function is not being called when dynamically injecting HTML and binding the click event. Below ...

Why is my Typescript event preventDefault function ineffective?

Despite all my efforts, I am still unable to prevent the following a tag from refreshing the page every time it's clicked. <p> <a onClick={(e) => handleClick} href="&qu ...

Using only the first letter of a contraction as uppercase

One of the challenges I'm facing right now is how to properly capitalize the first letter of each word in a string while keeping all other letters in lowercase. Although I've dedicated countless hours to working on this, my code appears to be abo ...

I can't quite understand the reasoning behind why this specific function is designed to output

I've been working on a JavaScript exercise and struggling to understand the logic behind it. The exercise involves a function named "mystery" that utilizes several basic functions to return an array in reversed order. Despite spending hours trying to ...

Reorganizing an array using a custom prioritized list

Is it possible to sort an array but override precedence for certain words by placing them at the end using a place_last_lookup array? input_place_last_lookup = ["not","in"]; input_array = [ "good", "in", "all&qu ...

Is it possible to expand the Angular Material Data Table Header Row to align with the width of the row content?

Issue with Angular Material Data Table Layout Link to relevant feature request on GitHub On this StackBlitz demo, the issue of rows bleeding through the header when scrolling to the right and the row lines not expanding past viewport width is evident. Ho ...

Words next to picture

Can someone help me with aligning different images of varying widths but the same height inline with text next to each image? I tried to do it, but it doesn't look good on responsive screens. Any suggestions on how to fix this? And if there's a b ...

What is the process for displaying user input on the console?

How can I ensure that the server is receiving user input? What steps should I take to print this input to the console? Currently, the console.log statement only displays "About to create new room", but I require the user input as well. Client-Side: // C ...