What is the most efficient method for swapping out a portion of an array with a different one in Javascript?

Currently experimenting with Dygraph and have successfully integrated a reloader feature that adds high-resolution data as users zoom in on the graph.

To maintain the original file boundaries, I am preserving the existing data and inserting the newly loaded data at the respective zoom intervals using the following method:

function optimizeDataReplacement(graph_tool, high_res_data) {
  ...
  
  for (i = 0; i < current_set.length; i++) {
    point = current_set[i];
    // NOTE: Each point is [time_in_milliseconds, value_for_graph]
    time_value = point[0];

    if (time_value < lower_limit || time_value > higher_limit) {
      new_set.push(point);
    } else if (is_replaced === undefined) {
      is_replaced = true;
      new_set = new_set.concat(high_res_data_set);
    }
  }
  ...
}

I'm curious if there's a more efficient way to achieve this, as the performance of graph rendering noticeably decreases with increased data volume.

Question:
What is the quickest method to substitute a section of an array with another array?

Appreciate the insights!

Answer №1

If you have the knowledge of the indices in advance and wish to make changes to the array using the original splice method is likely the most efficient method - although for better performance it is recommended to compare it with a customized solution that manually handles the data movement.

If your intention is to construct a new array, this code snippet might be useful:

var len = current_data_set.length,
    new_data_set = new Array(len);
for (var i=0; i<len; i++)
  var point = current_data_set[i];
  if (point[0] < lower_bound)
    new_data_set[i] = point;
  else
    break;
for (var j=i, k=0, l=hi_res_data_set.length; k<l; k++)
  new_data_set[j++] = hi_res_data_set[k];
for (; i<len; i++)
  if (current_data_set[i][0] > higher_bound)
    break;
for (; i<len; i++)
  new_data_set[j++] = current_data_set[i];

In my opinion, this method could be faster than yours because

  • it avoids using concat which generates an additional new array
  • it does not evaluate all points against lower_bound and higher_bound
  • it eliminates the need for the peculiar is_injected variable (which should ideally have a boolean data type), used mainly to skip over a certain section of the loop

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 could be causing the count button to malfunction on my Oracle APEX form?

I am working on creating 2 buttons that can adjust the quantity of products on an orderline, either increasing or decreasing it. https://i.sstatic.net/kFOkP.png My goal is to have the plus and minus buttons modify the quantity value when clicked. I att ...

Formatting numbers in Angular 2 to include a space every three zeros in a money amount

Let's say I have the number 30000 and I want to format it as 30 000. What method should I use to achieve this? Here are more examples: 300000 -> 300 000, 3000000 -> 3 000 000. Just to clarify, this is not about using dots or commas, but rathe ...

Automatically fill in checkboxes based on user input

Having a simple problem here, I am attempting to dynamically populate check-boxes in an HTML form. However, when I try using the checked property of the checkbox in HTML, it doesn't work correctly. The checkbox remains checked whether I use checked=&a ...

How to troubleshoot missing API data in a Bootstrap 5 modal

I am currently working on a project involving a Pokemon API where I have successfully built the front end using .fetch(). My goal is to create an additional modal that displays some stats. However, I am struggling to get the data from the API to show up in ...

single calendar bootstrap-datepicker allowing users to select date ranges

Is it possible to create a single calendar range date picker with Bootstrap instead of using two separate calendars? Currently, I have implemented a solution with two calendars. $('#datepicker').datepicker({ }); <link href="https://cdnjs.cl ...

Shifting Angular Component Declarations to a New Location

Here's a question that might sound silly: In my Angular project, I am looking to reorganize my component declarations by moving them from angular.module.ts to modules/modules.modules.ts. The goal is to structure my src/app directory as follows: src ...

Issue with Jest mock function failing to trigger axios instance function causing it to return undefined

I initially found a solution on this StackOverflow thread However, I wanted to add my own helper function that generates a fresh Axios instance with the user's authentication token. Here is what I came up with: import axios from "axios"; c ...

What is the correct method for configuring access permissions?

I'm in the process of developing a user management system, but I keep finding myself having to check the user type for each router. router.get('/admin/settings', (req, res) => { if(admin) { //Proceed. } } router.get(&apo ...

What is the method to trigger the jQuery 'mouseenter' event on an element using Selenium?

Struggling to automate a scenario using selenium where I need to click on a menu element. I've tried various methods, except jQuery. WebDriver normal click and JavaScript click() haven't worked. Can someone assist me with implementing jQuery in s ...

Blending an HTML jQuery toggle

Is there a way to make the current headline fade out while simultaneously fading in a new one when switching to the next div using a jQuery .html switch? Check out the codepen example: https://codepen.io/balke/pen/JpNNve $(window).scroll(function() { ...

Unable to change the structure of a multidimensional array in PHP

I am faced with the challenge of working with two arrays. The first array ($dcel) is structured like this: Array( [1] => Array ( [V1] => 5 [V2] => 2 [F1] => 4 [F2] => 1 [P1] => 7 [P2] = ...

How can CakePhp's $ajax->link be used to manipulate the result on the complete action?

Recently, I've started working with cakePhp to handle ajax requests using prototype. While my controller is returning the correct value, I'm struggling to figure out how to properly handle it when it comes back looking like this: <?php echo ...

Divide the string once it reaches the initial appearance of a character following a specified matching string

Data Breakdown: { \"value\": 17.11, \"year\": 2015, \"sub\": [ {\"x\": 0, \"y\": 0.94 }, {\"x\": 1, \"y\": 1.08 }] } , { \"value\": 17.23, \"year\": 2015 ...

Sorting through a table based on the name of the element

I am currently working on filtering an HTML table using a search form. It's working great, but I'm facing an issue where the filtered elements are trying to fill the entire width of the table instead of maintaining their original width (which is ...

Displaying markers on a Google map by fetching data from a MySQL database in PHP

The image attached here serves as an example. You can view it here. Currently, I display locations on a map in an HTML page with static code like: Here is the JavaScript code to load the map on the page: <script type="text/javascript" src="https://ma ...

Using jquery to toggle the visibility of input fields

I'm encountering an issue with this straightforward code snippet: $("#additional-room").hide(); var numAdd = 0; $("#add-room").click(function(e) { e.preventDefault(); $("#additional-room").show(""); if (numAdd >= 3) return; numAd ...

Contrasting $interval and setInterval functions in AngularJs

I am trying to grasp the distinction between $interval and setInterval. I have come up with this test: Dashboard.prototype.updateTotalAppointments = function(){ //console.log(); this.appointmentsCount = this.appointmentsCount +1; console.log(this.appointm ...

When trying to upload numerous files, only a single file ends up being

The issue is with the function that is only uploading 1 file instead of all 6 files. It seems to be returning an array $fileDirectories with a dimension of 1, whereas I expected it to have 6 dimensions. The interesting thing is that count($_FILES['fil ...

How to save array data to a text file using node.js

I have an array containing values that I want to write to a text file using the following code. while(filedataarr.length>0) { firstelement = filedataarr.shift(); //console.log(firstelement); fs.appendFile("D:\\Temp& ...

Using Redux Form to set the default checked radio button in a form setting

I'm currently attempting to make a radio button default checked by using the code below: import { Field } from "redux-form"; <Field name={radio_name} component={renderField} type="radio" checked={true} value={val1} label="val1"/> <Field na ...