Generating arrays dynamically with JavaScript

I'm attempting to dynamically generate an array from another array in JavaScript. The task at hand involves taking a string that represents a mathematical literal expression, such as '2a + 3b + 4a + 5c', and splitting it into an array containing only the literal parts of the equation (e.g., 'a,b,a,c').

My initial approach was to use the following code snippet:

var expression = '2a + 3b + 4a + 5c';
var NumbersArray = expression.split(' + '); /* NumbersArray = 2a,3b,4a,5c */
alert('So far it's working!');
var LettersArray = new Array();
for (var i = 0; i < NumbersArray.length; i++) {
    eval('var LettersArray[' + i + '] = NumbersArray[' + i + '].replace(/[0-9]/g,"");');
    alert(eval('LettersArray[' + i + ']'));
}

Despite my efforts, the code didn't produce the desired outcome. How can I rectify this issue?

Answer №1

Encountering numerous mistakes in this code snippet, so here are the corrections I made:

var expression = '2a + 3b + 4a + 5c';
var NumbersArray = expression.split(' + '); /* NumbersArray = 2a,3b,4a,5c */

//It's better to use double quotes instead of single quotes inside single quotes to avoid issues
alert("Seems like it's working fine!");

//Prefer using array literals [] over new Array() unless necessary
var LettersArray = [];

for (var i = 0; i < NumbersArray.length; i++) {
    //eval is unnecessary here and re-declaring LettersArray with var should be avoided
    LettersArray[i] = NumbersArray[i].replace(/[0-9]/g, '');
    alert(LettersArray[i]);
}

View a functioning example here: http://jsfiddle.net/FERj5/

An alternate method to achieve the same outcome more efficiently:

var expression = '2a + 3b + 4a + 5c';
var letters = expression.replace(/\d+/g, '').split(' + ');
//now letters == ['a', 'b', 'a', 'c']

Answer №2

In the scenario where you are converting from '2a + 3b + 4a + 5c' to 'a, b, a, c', there is a shorter way to accomplish this:

let expression = '2a + 3b + 4a + 5c';
expression.replace(/(\d+|\s+)/gi,'').split('+');

Answer №3

the alert message you have is causing an error. It should be:

 alert("So far it's working!");

There is also an issue with using eval in your loop.

This revised code will work correctly:

var expression = '2a + 3b + 4a + 5c';
var NumbersArray = expression.split(' + '); /* NumbersArray = 2a,3b,4a,5c */
var LettersArray = [];
var evalit;

for (var i = 0; i < NumbersArray.length; i++) {

    evalit = "LettersArray[" + i + "] = NumbersArray[" + i + "].replace(/[0-9]/g,'');";

    eval(evalit);
    alert(LettersArray[i]);
}

Check out the demo fiddle for reference.

Avoid using eval unnecessarily in your code.

Answer №4

Why resort to eval when there are simpler alternatives available? Give this code a try:

let equation = '2x + 3y + 4x + 5z';
let numbersArray = equation.split(' + '); /* NumbersArray = 2x, 3y, 4x, 5z */
let lettersArray = [];

for (let i = 0; i < numbersArray.length; i++) {

    lettersArray[i] = numbersArray[i].replace(/[0-9]/g,"");
    console.log(lettersArray[i]);
}

Answer №5

Is there a specific level of flexibility required for this situation? If the pattern you are dealing with will consistently follow the format of

[number][letter] + [number][letter] + [number][letter] + [number][letter] + ....
, then a simple approach could suffice:

var formula = '2a + 3b + 4a + 5c';
var NumbersArray = formula.split(' + '); /* NumbersArray = 2a,3b,4a,5c */
var LettersArray = formula.match(/[a-z]/g); /* LettersArray = a,b,a,c */

If you require a bit more adaptability, adjusting the regular expression pattern would provide additional options:

  • In case multi-letter variables need to be considered, modify /[a-z]/g to /[a-z]+/g.
  • To include uppercase variables as well, change /[a-z]/g to /[a-z]+/gi.

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

The value of `this` from React Store is currently returning null

I'm facing an issue where the this keyword is coming back as null in my store within a React component. I suspect that binding might be necessary, but I'm not entirely sure. Additionally, I am utilizing React Router and have the component wrapped ...

I am unable to sketch my backdrop. - HTML Canvas Game

Recently I've encountered an issue in my code where the image doesn't appear and mouse interaction stops working when I uncomment bg.draw() within the draw function. function draw() { clearAllCtx(); player.draw(); ene ...

Utilizing a for loop to gather user inputs and store them in an array

Is it possible to use a for loop to prompt the user to input 10 values? I am encountering an error with the "<" symbol between count and Values. Any ideas on how to resolve this issue? void EnterValues() { int UserValues[10]; //creating array t ...

Execute a sorted operation with proper authorization

Recently, I developed a NextJs dashboard that enables Discord users to connect to their accounts. One of the main features is retrieving the user's guilds and filtering them to include only the ones where the user has either the MANAGE_GUILD permissio ...

Updating a single component within a changing array of objects in React: Best practices

I've got a question regarding React rendering that I need help with. Before I dive into the explanation, here's the link to the relevant code sandbox: https://codesandbox.io/s/list-rerendering-y3iust?file=/src/App.js Here's the situation - ...

Attaching a modal to an entity

I am currently working on binding a Knockout (KO) viewmodel to a Bootstrap modal, but it seems like I am overlooking a step to direct KO to fill in the input fields. Below is the current setup: The template for the modal: <script type="text/html" id= ...

Leveraging the Power of jsPDF in Your Google Apps Scripts

Is it feasible to integrate jsPDF into a Google Apps Script project? I am attempting to create documents using templated HTML, but certain CSS styles like background-color do not translate to PDF when using the getAs() function. Given the limitations of ...

What is the best way to access a promise's value in global scope within a reactjs application?

Currently tackling user authentication using web tokens in react. My approach involves utilizing the fetch() method to send a POST request to my backend, facilitating CORS. The issue arises when attempting to employ the setToken() hook within the .then() b ...

What is the method for displaying an array separately for each item in JSON using JavaScript?

The issue arises when using for (let pet of person.pets) loop. In my JSON data, the "pets" field is an array but instead of getting a single array for each object, I am getting all pet arrays for every object in the JSON file. The desired outcome is to h ...

"Enhance Your Coding Experience with Visual Studio Code - TypeScript Definitions Catered

I am currently working on developing a basic web application using Node.js and Express. I have successfully installed both definitions using tsd following the steps outlined in this guide. When I run tsd query mongodb --action install, I do not encounter ...

Updating certain fields in AngularJS with fresh data

I am facing a challenge with the following code snippet: <div ng-controller="postsController"> <div id = "post_id_{{post.postid}}" class = "post" ng-repeat="post in posts"> ...... <div class="comments"> < ...

Using the output from the previous node, populate the form on the NodeRed node with the message

I have a pair of custom nodes that connect to a web service to retrieve data using atomic IDs. My goal is to fetch all items (an array of JSON payloads) with one node, append it to the msg payload, and then utilize that payload in an .on("input") event to ...

Transform a string containing spaces into a uint16 data type

Hi, I'm seeking assistance with converting a string into an array of uint16. Here is an example of how my string appears: Dim test as String = "4 7 9 10 11 12 14 15 16 17 19 23 24 25 26 27 28 29 30 32 33 37 40 42 48 58 64 65 66 67 68 69 70 71 72 73 ...

Detecting collision between two moving objects in Three.js with the use of a Ray

I am currently working on developing a 3D breakout game using THREE.js and WebGL rendering technology. My goal is to utilize THREE.Ray to detect collisions between the bouncing ball and the controllable platform at the bottom. However, I am encountering so ...

Developing a HTML button through Javascript that triggers a method with a single parameter when clicked

My current project involves creating HTML buttons through JavaScript using AJAX. Each time I click one of these buttons, it triggers an AJAX function. If the AJAX request is successful, it retrieves a number that will be utilized in a for loop. As the loop ...

Java has trouble decoding non-ASCII characters sent through Ajax

When I send an AJAX request using jQuery post() and serialize, the encoding used is UTF-8. For instance, if 'ś' is input as a name value, JavaScript displays name=%C5%9B. Despite my attempts to set form encoding, it has not been successful. < ...

Showing Div content from AngularJS response

Query -- I am currently using a Controller in AngularJs that performs an $http.get request and receives data as a response. The data includes an HTML DivID and corresponding classes. How can I extract this DivID from the response and transfer it to the vi ...

Teach me the steps in a promise chain to send a response and conclude the flow of the promise

Whenever I run the code below, I encounter this particular error message: Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client when result === null. 'use strict' const HttpStatus = require(&a ...

My attempts to utilize AJAX to execute a php function have been unsuccessful

Having trouble getting an ajax call to trigger a php function and return successfully. The syntax seems correct, but all I'm getting back is "failed." Any ideas? EDIT I tried changing my AJAX request to send without using data, ruling out that as a ...

Error: The JavaScript SRC cheat is malfunctioning

Having an issue with the code below. The 'dummy1' and 'dummy2' variables are not loading their content as expected on the page. Any suggestions? <html> <head> <title>JavaScript On-line Test</title> <script LA ...