What strategies can I use to optimize an eval loop in JavaScript?

Upon taking over a codebase, I was greeted with this particular coding style devoid of any tests:

  var series1 = [];
  var series2 = [];
  var series3 = [];
  var series4 = [];
  var series5 = [];
  var series6 = [];
  var series7 = [];
  var series8 = [];
  for (var y = 1; y <= seriesData.length; y++) {
      // columns are series
      eval("series" + y).push({
        label: "series" + y,
        lineColor: colorArr[seriesData[y - 1].colorIndex],
        x: sampleTime,
        y: rows[x][seriesData[y - 1].index]
      });
  } 

An issue has arisen as we plan to accommodate more than just 8 sets of data. Personally, the existing code style irks me and there are concerns surrounding the use of the eval function in JavaScript. Is there a more efficient way to revamp this?

My attempted solution so far:

  let multiarr = []
  for (var y = 1; y <= seriesData.length; y++) {
    // columns are series
    let arr = [];
    arr.push({
      label: "series" + y,
      lineColor: colorArr[seriesData[y - 1].colorIndex],
      x: sampleTime,
      y: rows[x][seriesData[y - 1].index]
    });

  }
  multiarr.push(arr);

Answer №1

The original code appears somewhat unconventional. It contains an array of series, but each array only contains one item. Could it be simplified to:

const result = seriesData.map((item, i) => ({
  label: `series${i + i}`,
  lineColor: colorArr[item.colorIndex],
  x: sampleTime,
  y: rows[x][item.index]
}))

If there is a specific reason for each item to be within its own array, you can achieve this by:

const multiarr = seriesData.map((item, i) => [{
  label: `series${i + i}`,
  lineColor: colorArr[item.colorIndex],
  x: sampleTime,
  y: rows[x][item.index]
}])

Answer №2

To streamline the process, you can combine all arrays into a single array and then use an index to push the elements.

let seriesOne = [],
    seriesTwo = [],
    seriesThree = [],
    seriesFour = [],
    seriesFive = [],
    seriesSix = [],
    seriesSeven = [],
    seriesEight = [],
    dataCollection = [seriesOne, seriesTwo, seriesThree, seriesFour, seriesFive, seriesSix, seriesSeven, seriesEight];

for (let y = 0; y < seriesData.length; y++) {
    dataCollection[y].push({
        label: "series" + (y + 1),
        lineColor: colorArr[seriesData[y].colorIndex],
        x: sampleTime,
        y: rows[x][seriesData[y].index]
    });
}

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

Deleting a nested object from an array within another object

Recently, I delved into the world of Redux and have found it quite fascinating. However, I am currently facing a dilemma where my new reducer function inadvertently changes the type of a state variable, which is not what I intended. The desired structure ...

Angular 2, the change event is not triggering when a bootstrap checkbox is clicked

Encountering an issue, the (change) function is not triggering in a specific checkbox. <input [(ngModel)]="driver.glasses" name="glasses" type="checkbox" class="make-switch" (change)="changeFunction()" data-on-color="primary" data-off-color="info"&g ...

Utilizing object UUID keys to associate products in VueJS

Hey there, I've gone ahead and created an object with UUIDs but now I'm looking for a way to link these UUIDs to specific items. It seems like there needs to be some separation between the UUID and the rest of the object, however, my main issue i ...

Combining hash arrays in Ruby

I'm currently working on combining multiple arrays of hashes in Ruby using a shared key. Here's an example to illustrate: country_info = [ {country_id: "US", country_desc: "United States"}, {country_id: "AU", country_desc: "Australia"} ] co ...

Validating radio buttons in JS after submitting a form using PHP $_POST

I am dealing with a form that contains a variable number of radio buttons: <input id='create' name="post[]" type="radio" value="<? echo $newphrase; ?>" /> My goal is to validate the form to ensure that at least one button is select ...

Discover a sophisticated approach to handling a lone input in the absence of keys within an array of arrays

I am currently working with an SQL data pull format that is stored in the variable $data. YEAR QUARTER CAT NAME ASSMT_TOTAL 2011 Q2 2011-Q2 Place-1 18 2011 Q3 2011-Q3 Place-1 22 2011 Q4 2011-Q4 Place-2 34 2011 Q3 2011-Q3 Place-2 21 2 ...

Employing both Angular 1 and Angular 2 in conjunction

As a newcomer to angular, this is my first experience. My ultimate goal is to incorporate the following component into Angular 2: While I have some knowledge of JavaScript, I am attempting to integrate an Angular 1 library into an Angular 2 project. Aft ...

What could be causing my variables to not update in Node.js?

I recently developed a web application using node.js that is designed to receive messages from an SNS topic through a POST request. The messages are then logged to the console and displayed on the webpage. However, I noticed that when I publish a message t ...

Issue encountered while utilizing function to retrieve an array

I'm facing some challenges while attempting to use a function that returns a 1D array for my subroutine. The code snippet below provides a simplified version of the issue I am encountering: Sub test() Dim testArry(1 To 3) As Double testArry = arryFu ...

Single quotation mishap in JSON

How can I successfully send JSON data that contains single quotes without encountering errors? I need to include values with single quotes, but how can I do this without causing any issues? $.ajax({ type: "post", url: "canliAyarlari.aspx/dosyaYa ...

Is there a way to verify the existence of an array in fish?

Although the method I am currently using seems to be effective in this specific scenario, when I initially searched for solutions, I couldn't find any queries related to this. Here is an example of how I currently verify arrays: # Example array, $arr ...

Conditionally displaying an input model in Vue.js using v-if

Just starting to learn vue.js and I'm looking to display table data. My idea is that when the table is in display mode, it should only show the data. However, when I click on the edit button of a table row, I want that specific row to switch to edit m ...

Collaborating and monitoring data between controllers

A unique challenge has arisen as we implement a tree-style navigation element that must communicate with other directives/controllers. The main objectives are: Keep track of the current selection, Detect when the row selection changes. The task at hand ...

Utilizing Conditional Statements in the @artsy/fresnel Framework

I recently started working on a responsive React application using the @artsy/fresnel npm package. Below is a snippet of the code I have implemented: <Media greaterThanOrEqual='computer'> <div style={{ padding: '20px 50px' ...

Creating vibrant row displays in Vue.js: A guide to styling each row uniquely

I am not a front-end developer, so Vue and JS are new concepts for me. Currently, I am working on an application for managing sales. One of the components in my project involves displaying invoices in a list format. To make the rows visually appealing, I ...

Java's tostring() function is showing unusual values

My attempt to create a string reversal algorithm involved using two pointers, one at each end of the string. One pointer (i) points to the beginning while the other pointer (j) points to the end. The elements located at these positions are swapped and then ...

Refresh all fields for various products with a single click of a button

Our Magento multi-vendor site allows vendors to easily manage their products. For each single product, vendors can view and update information such as price, selling price, quantity, and more from their vendor account. We have implemented a feature where ...

Create a std::array<T, N> with a large N=256 value for a complex type

Does anyone have a solution for populating an std::array<T, N> with T being a non-default-constructible struct/class and N known at compile time but too large to hard-code each element individually (e.g., N=256)? The constructor in my case takes one ...

Is it possible to match a String with the identifier of an array?

Hey there! I'm currently working on a project where I need to extract details for a specific item from one array by referencing another array. Here's the code snippet I have so far: foreach($json_items['result']['items'] as $ ...

Navigating through a dropdown menu using Selenium in Javascript for Excel VBA - Tips and tricks

I need to access a web page using Excel VBA that is only compatible with Chrome or Firefox, not Internet Explorer. I have successfully accessed the website using Selenium, but I am having trouble navigating through the drop-down menu to reach the section w ...