Adding missing values to two corresponding arrays in JavaScript

I am working with two arrays:

  1. xAxisData: ["0006", "0007", "0009", "0011", "0301"]
  2. yAxisData: [6.31412, 42.4245, 533.2234, 2345.5413, 3215.24]

My goal is to standardize the length of the xAxis array to a maximum value, for example, DATAPOINT_LENGTH_STANDARD = 540. This involves filling in any missing number-based strings in the xAxis array to achieve the following:

  1. The updated xAxis array should range from "0000" to "0540" (or any other standard length)
  2. The corresponding yAxis values should remain associated with their original xAxis data points (e.g. "0006" corresponds to 6.31412)
  3. Any newly added xAxis data points should have a yAxis value of 0 (e.g. the new entry "0000" will have a yAxis value of 0)

It is safe to assume that the xAxis value strings are already sorted from lowest to highest.

UPDATE:

In response to feedback, I attempted to clarify my question for the benefit of the community. However, it seems the level of detail may have made it appear like a homework assignment. Here is my original attempt, which did not fully manipulate the x-axis and maintain correct indexing:

let tempArray = categoryObject.data.xAxis;
let min = Math.min.apply(null, tempArray);
let max = Math.max.apply(null, tempArray);
while (min <= max) {
  if (tempArray.indexOf(min.toString()) === -1) {
      tempArray.push(min.toString());
      categoryObject.data.yAxis.push(0);
  }
  min++;
}
console.log(tempArray);
console.log(categoryObject.data.yAxis);

Answer №1

const xValues = ["0006", "0007", "0009", "0011", "0301"]
const yValues = [6.31412, 42.4245, 533.2234, 2345.5413, 3215.24]
const STANDARD_LENGTH = 540

// Adjust the length of the data points array
let paddedLength = xValues[0].length
let newYValues = new Array(STANDARD_LENGTH + 1).fill(0)

xValues.forEach((x, index) => newYValues[+x] = yValues[index])

yValues = newYValues

for (let i = 0; i <= STANDARD_LENGTH; ++i) {
  xValues[i] = ('' + i).padStart(paddedLength, '0')
}

console.log(xValues)
console.log(yValues)

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

What is the purpose of the `Bitwise operator |` in the `d3.shuffle` source code and how can it be understood

Learning about the Bitwise operator | can be found in the document here and a helpful video tutorial here. However, understanding the purpose and significance of | may not come easily through basic examples in those resources. In my exploration of the sou ...

Updating the checklist status using an ajax request: A step-by-step guide

Is it better to update the checklist status by making individual ajax calls for each checklist item or by making one call and updating it once completed? I have included a template showing how it currently looks and what I am aiming for. Unfortunately, I ...

remove an element from a nested array using MongoDB

Greetings everyone! I am currently working on a materials document that contains arrays of articles, each article having an array of details. Here is a snippet from my collection data: { "_id": "62f2404b42556d62e2939466", "code&quo ...

Is it possible to pass multiple functions to the parent component in ReactJs if using OnChange() as a prop?

Just getting started with React and trying to pass data from a child component to a parent component. <div className="filter-module"> <i className="fas fa-sign-in-alt icon"></i> < ...

Transitioning to TypeScript has brought the promise of imports returning once again

I've been facing some challenges while migrating my extensive project to TypeScript, particularly with handling imports. Being relatively new to programming, I'm unsure if my previous approach was considered bad practice. Previously, I organized ...

Synchronizing two navigation menus on a single-page application website

Let me start by saying that I specialize in back end development and am facing a specific challenge with building a website that includes two navigation menus. The main navigation menu features links like Home, while the sub-navigation menu includes option ...

Typescript, left untranspiled in Karma test runs

I am attempting to conduct karma tests against Typescript. I have successfully installed karma and can run tests, but encounter Syntax Errors when my *.ts files contain Typescript syntax like this: Error: (SystemJS) SyntaxError: Unexpected token ) It s ...

Utilizing a React object incorporating "$$typeof" with the Symbol(react.element), for the purpose of inserting CSS classes

I'm currently working on enhancing the calendar by dynamically adding a CSS class to each day. For reference, I'm using the Material-UI Pickers library, and the DatePicker API is quite helpful: It seems like the key to achieving this is through ...

Receiving an error while trying to install packages from the NPM registry due to non

I am facing some challenges while attempting to install my Ionic App through the registry along with its dependencies. I have been using npm i --loglevel verbose command, and my ~/.npmrc file is configured as follows: //nexus.OMMITED.com/repository/:_auth ...

I encountered a data discrepancy while attempting to link up with a weather API

This is my debut app venture utilizing node.js and express for the first time. The concept behind this basic application involves connecting to an external API to retrieve temperature data, while also allowing users to input their zip code and feelings whi ...

What is the optimal method for assigning a value to a specific key within a JavaScript JSON object?

Below is the information stored in a file called "fokontanys.json": { "vzdveg643": { "lldistrict":"Ambilobe", "id_province": 7, "id": null }, "vzvsdv5327": { "lldistrict ...

The functionality of saving a file using the jsPDF method is not functioning properly

After dedicating four days to resolving a seemingly straightforward task that involved the jsPDF library, I found myself faced with a challenge. My goal was to save a file using this library, not just print it like I had successfully done before. This is ...

Guidelines for managing UnprocessedItems with the AWS JavaScript SDK for dynamoDB

Currently, I'm facing an issue while attempting to utilize an AWS Lambda function for handling events from SendGrid. The event is expected to be in the form of an array containing a variable number of JSON objects, each representing a specific event. ...

Switching elements in an array using Vue.js

Within my vue.js web application, I am attempting to switch the positions of two rows in a forum. Below is the code snippet I am using: export default { data() { return { forums: [] } }, met ...

Angular: What methods can I utilize to prevent my $http requests from causing UI blockage?

The following code snippet is from my controller: PartnersService.GetNonPartnerBanks().success(function (data) { vm.nonPartnerBanksList = data; }).error( function () { vm.nonPartnerBanksList = []; }); This code calls the service s ...

Designing a versatile pop-up window with jQuery or JavaScript that functions seamlessly across all web browsers

I've encountered an issue with my code where it displays a popup message correctly in Chrome, but when testing it on Firefox and Edge, it creates a strange box at the end of the page instead. Here is the code snippet I'm referring to: var iframe ...

Why do certain URLs bypass the filters despite not meeting the criteria in the Chrome extension?

I am currently developing a Chrome extension that is designed to automatically close tabs when specific URLs are visited, helping me stay focused and avoid distractions. The list of sites that should trigger tab closures includes: YouTube Facebook Reddit ...

Implementing a class for a dropdown menu within a JavaScript function

I recently came across a code that I am interested in using on my form to automatically select an option when clicking on a div. $("div").on("click", function(e) { var $select = $("select"); $select.val($(this).data("value")); // simulate cli ...

Passing slots to child components within a VueJS application - A helpful guide

Within my application, I frequently utilize a list and list_item component. To provide a general idea: contact_list.vue <template lang="pug"> .table .table-header.table-row .table-col Contact .table-col Info .tabl ...

Enforcement of static methods in Typescript abstract classes is not mandatory

In my TypeScript code, I have a simple structure defined: abstract class Config { readonly NAME: string; readonly TITLE: string; static CoreInterface: () => any } class Test implements Config { readonly NAME: string; readonly TITL ...