Building and filling a fixed-width array in JavaScript

I have a collection of data in the following format:

[[timestamp, jobid, time to completion],[..]]

This data is sourced from a SQL database and is grouped by timestamp and jobid. The array looks like this:

[  
[1, 30, 400],  
[1, 31, 200],  
[2, 29, 300],  
..  
]

My goal is to rearrange this data into a new array where each row corresponds to a timestamp and each column represents a specific jobid.

To achieve this, I initially attempted iterating through the existing array and populating a new one. However, the resulting array ended up being variable in width, making it difficult to identify which values corresponded to each job ID.

What I desire is an output that resembles the following structure:

timestamp, jobid29, jobid30, jobid31  
[  
[1, 0, 400, 200],  
[2, 300, 0, 0],  
..  
]

Unfortunately, outputting as a map is not an option for me.

How would you suggest achieving this? My current plan involves first identifying all distinct jobids within the input and then mapping each jobid to a specific position in the output array. Is there a better approach?

Appreciate your insights.

Answer №1

My approach involves utilizing two arrays and two maps with numerous possibilities for enhancement opportunities. Allow me to outline the general plan:

  1. Begin by sorting your array based on the jobID. (let's refer to this as the "jobList")

  2. Maintain a "map" that is organized by unique timestamps. ("timeStampMap"). Each unique timestamp should have an entry in this map.

  3. Create another array consisting of unique timestamps, which should also be sorted. ("timeList")

  4. Every item in the "timeStampMap" contains another map storing jobs associated with that particular timestamp value

  5. Iterate through each value in the timestamp list.

    During each iteration, go through every job in the jobList. If the job exists in the corresponding timestamp map, output the job's completion time.

    If not found, output zero.

There are two potential optimizations that can be applied to the code provided below: 1. It may be possible to utilize the input array directly as the "jobList" without requiring duplication. 2. Combining the map of maps into a single large map might also be feasible.

function jobSorter(a,b) {
    return a.jobID - b.jobID;
}

function numberSort(a,b) {
    return a - b;
}


function buildSortedArray(yourArray) {

    var index, j, item;
    var jobList = []; // array of {jobID, timeStamp, timeComp};
    var timeStampMap = {};
    var timeStampList = [];
    var key, jobkey;
    var output = [];

    // loop through every item in the array
    for (index = 0; index < yourArray.length; index++) {
        item = yourArray[index];         

        // push each item into a "job list"
        job = {jobID: item[1], timeStamp: item[0], timeComp: item[2]};
        jobList.push(job);

        // now use both a map and a list to keep track of all the unique timestamps
        key = "$timestamp$" + job.timeStamp.toString();

        if (timeStampMap[key] === undefined) {
            timeStampMap[key] = {};
            timeStampMap[key].jobMap = {};

            timeStampList.push(job.timeStamp); // keep another timestamp array that we can sort on
        }

        // add this job to the timestamp
        jobkey = "$jobid$" + job.jobID.toString();
        timeStampMap[key].jobMap[jobkey] = job;
    }

    // let's do some sorting
    timeStampList.sort(numberSort); // timeStampList is now in ascending order
    jobList.Sort(jobSorter);        // jobList is now in ascending order


    for (index = 0; index < timeStampList.length; index++) {
        item = [];

        item.push(timeStampList[index]);
        for (j = 0; j < jobList.length; j++) {

            key = "$timestamp$" + timeStampList[index].toString();
            jobkey = "$jobid$"  + jobList[j].toString();

            if (timeStampMap[key].jobMap[jobkey]) {
                item.push(timeStampMap[key].jobMap[jobkey].timeComp);
            }
            else {
              item.push(0);
            }
        }

        output.push(item);
    }


    return output;
}

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

"Create a HTML Form with a Submit Button that Does Not Refresh the Page

I created a form with fields for Name and Email, along with a submit button. The submit button is set to trigger the invite() JavaScript method upon being clicked. <form id="inviteForm" action=""> <div class="modal-body"> ...

Why is my Express Router being called twice?

When I call server.js, it in turn calls index.js via a route. The issue I am facing is that the router in index.js is being called twice when the page is accessed, resulting in the message "/ (Console.log inside router.use(async (req, res, next) => { fr ...

Experiencing unexpected output from Angular model class method

I have developed a user-friendly Invoicing & Inventory management application that showcases a list of invoices for each customer. However, there seems to be an issue with the calculation of the Grand Total function, which I am struggling to rectify due to ...

Running an Angular application on Vercel with necessary libraries

Whenever I attempt to host my Angular application on Vercel, I encounter the following issue: Error: src/app/spotify.service.ts:25:32 - error TS2339: Property 'spotifyApiKey' does not exist on type '{ production: boolean; }'. This er ...

Updating your data: Transforming deeply nested JSON elements into a more manageable list

I'm struggling to convert the JSON response into a list of "properties" elements. The structure of my JSON is as follows: { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { ...

Fetching picture from the database using AJAX and adding it in Laravel version 5.4

I've been using an AJAX request to fetch data from my database and then appending it to a div. However, I've run into an issue with the image source. My image files are stored in a public folder named "image_files". The problem arises when trying ...

"Resetting count feature in AngularJS: A step-by-step guide

I have a list consisting of four items, each with its own counter. Whenever we click on an item, the count increases. I am looking to reset the counter value back to zero for all items except the one that was clicked. You can view the demonstration here. ...

Tips for displaying or concealing a particular form when a link is clicked, among multiple forms sharing the same class identifier

I am facing an issue with multiple forms and links that toggle them being appended to a page after a specific action. My goal is to have each link associated with a form toggle its respective form's visibility. However, I am currently encountering an ...

Utilizing an Angular framework to access external JavaScript libraries when the document is fully

I'm incorporating a third-party JavaScript library into my .NET Core ASP Angular application. This library executes its functionality within the $(document).ready method. However, I've encountered an issue where the library's logic isn' ...

Transforming text input into an array of text in PostgreSQL

I have a table named t1 id | names ----|------------------------- 1 | {jully , alex , sarah} 2 | {bety , cate , jenifer} 3 | {adam , pit , joee} 4 | {piter , mat , andy} My goal is to retrieve rows that contain at least one name starting wi ...

"Troubleshooting a Animation Problem in the Latest Version of

I have discovered an issue with animations on the latest version of Firefox Quantum. Upon loading a page with certain animated elements set to display: none;, when a script changes it to .display = "block";, some parts of the animation may be missed or no ...

Storing the JSON response from axios into a variable: a beginner's guide

Exploring the concept of saving the JSON data returned from axios into a variable has left me puzzled. Currently, I am only able to visualize it when I utilize console.log(response.data) with the code snippet below: function status() { const url = " ...

Sorting objects in Java alphabetically

In my Library class, I have created a Books class that extends it. This Books class contains various attributes such as registration number, author, name, year of publishing, publishing house, and number of pages. It also includes a constructor to initiali ...

Creating a list that renders responsively using ReactJS

I'm currently working on implementing a responsive search bar that filters through a list of pure components (up to 100 components displayed at once). However, I've noticed there is a slight half-second delay between typing the first letter and s ...

Not sure about the Fat Arrow (=>) function

Hey there, I've been diving into NextJs and came across this issue: This Module is Functional const GlobalStyles = () => ( <> <Global styles={css` body { color: #000000; } `} ...

Please be advised that the message is currently in the process of being typed

In my current setup, I am utilizing Laravel 5.6.7, Socket.IO, and vue.js while excluding Pusher and Redis. The following is the code snippet I am using to send messages directly to a user engaged in one-on-one chatting with me. var url = "http://localhost ...

Whenever I attempt to give a name to my array, I encounter an error. However, strangely enough, if I leave it unnamed, everything works without any issues

I'm currently exploring the use of JSON to store a basic array of customer data that I can loop through later. However, I've encountered an issue when I try to assign a name to the array like "var customs" as it throws an error stating "Expected ...

What is the best way to check the contents of the text on the login page that appears a few seconds after the button is clicked

Currently, I am in the process of learning Selenium Webdriver and working on a code to populate a registration form for rediff.com. When opting for a rediffmail ID, there is a validation button that checks if the entered ID is available or not. If the ch ...

Using Typescript to dynamically set the length of a tuple or array based on the arguments passed to a function

Here is some TypeScript code to consider: function concatTuples<T>(first: [...T[]], second: [...T[]]): [...T[]] { return [...first, ...second]; } const result = concatTuples([0, 1], [2, 3]); This function concatenates tuples. The current challeng ...

The HTTP request seems to be malfunctioning

When attempting to establish a connection and retrieve data from a PHP file using an AJAX request, it's important to note that the AJAX JS is located on a different website. Here is the script being used: var quer; try { quer = new XMLHttpRequest( ...