Tips on organizing multiple arrays within a single array

I am retrieving an array from the backend that looks like this:

["[a,b,c],[c,d,e],[e,f,g]"]

Once I grab this array, I place it inside a

<div id="op1">{{$option}}</div> 

Now, I want to append additional items to it when I access it in JavaScript using

document.getElementById('op1').innerHTML 

and then add these items into another array like this

var options=[document.getElementById('op1').innerHTML];

When I print it out using

console.log(options)

it displays

["[a,b,c],[b,c,d],[e,f,g]"]

This is not the desired format of the array, which should look like this

[[a,b,c],[b,c,d],[e,f,g]]   

So my question is, how can I achieve the correct type of array and include more items in it?

Answer №1

Although I cannot guarantee that this answer is the most efficient solution, I have attempted to provide a solution that closely aligns with your requirements:

var arr = ["[a,b,c],[b,c,d],[e,f,g]"];
var res = [];
arr[0].split('[').forEach((splitVal) => {
  if (splitVal) {
    var arrInner = [];
    var commaSplit = splitVal.split(',');
    commaSplit.forEach((commaSplitVal) => {
      if (commaSplitVal) {
        arrInner.push(commaSplitVal.replace(']', ''));
      }
    });
    res.push(arrInner);
  }
});
console.log(res);

Answer №2

The given data state as shown above ["[x,y,z],[z,a,b],[b,c,d]"] is a JavaScript Array with a single item, which happens to be a string. This string comprises multiple arrays separated by commas.

You have the option to utilize String.prototype.split in order to divide the string into separate arrays using a designated separator.

var choices = [document.getElementById('choice').innerHTML];
var desiredArray = choices.map(element => element.split(','));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

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

Formatting dates in Angular 2 and handling them in MongoDB with Express

I am currently working with Angular 2 and ExpressJS along with MongoDB. I have a date format that is being retrieved as 2016-06-02T14:20:27.062Z, but I need to display it in the format 06/02/2016 14:20:27 Express: In models/user.js: var userSchema = Sch ...

Using asynchronous functions in a loop in Node.js

Although this question may have been asked before, I am struggling to understand how things work and that is why I am starting a new thread. con.query(sql,[req.params.quizId],(err,rows,fields)=>{ //rows contains questions if(err) throw err; ...

Need help tackling this issue: getting the error message "Route.post() is asking for a callback function, but received [object Undefined]

I am currently working on implementing a new contactUs page in my project that includes a form to store data in a mongoDB collection. However, after setting up all the controller and route files and launching the app, I encountered an error that I'm u ...

Can JavaScript impact the appearance of the printed version of a website?

Just a quick question - I currently don't have access to a printer. My client is wondering if the hidden elements of the webpage (items that are only visible when clicked on) will be included when printing or if they will remain hidden? ...

Utilizing ng-model to control the visibility of a label or anchor tag

Here is the code snippet I am working with: <div class="tabs DeliveryRightDiv"> <label class="selected"><a>One</a></label> <label> <a>Two</a> </label> <label> ...

What could be causing my for loop to become unresponsive?

My for loop seems to be populating all fields with the last object parsed. http://codepen.io/anon/pen/EKxNaN This is my current code. I created something similar on CodePen since I can't access JSON from the original source there. var championMaste ...

Revolutionizing messaging with Vue JS and Firebase

My web application is designed to check if a user has messages in the Firebase database. If messages are found, it retrieves the data from the users who sent those messages from my local database and displays them in a list using a v-for loop. The display ...

Learn the process of playing a video in an HTML5 video player after it has finished downloading

// HTML video tag <video id="myVideo" width="320" height="176" preload="auto" controls> <source src="/server/o//content/test2.mp4" onerror="alert('video not found')" type="video/mp4"> Your browser does not support HTML5 vid ...

Implementing Angular checkbox repetition controlled from an external controller

I'm looking to streamline my controller by setting a variable from outside the controller to populate my checkbox list. Can this be done? Check out my current code snippet here: http://jsfiddle.net/ilmansg/Lx37kr3e/1/ VIEW HTML <div ng-controlle ...

Refresh a webpage using JavaScript (inside a jquery ajax call)

Seeking guidance on how to reload a page using JavaScript, I have created the following function: function update(id, name) { if(/^\d+$/.test(id)) { $.ajax({ url: baseurl + "/url/action/param/" + id + "/param2/" + unescap ...

Retrieving the data stored in an associative array using JavaScript

I need to access a specific value from an array in JavaScript. Here is my array: [{"username1" : "123456"},{"username2" : "121"}] I want to retrieve the value of username1, specifically 123456. How can I achieve this? I have provided my current code belo ...

"When using the Fetch API to make a POST request, the req.body is found to

When attempting to call the POST API using the fetch method and passing parameters in the body, I encountered an issue where req.body was undefined on the Node.js backend side. However, when I called the same POST API through Postman with parameters in the ...

Is your $_POST acting oddly? It seems to be doing the opposite of what you'd

The HTML form provided below is submitted to the PHP file (workcard_done.php). There seems to be an issue when submitting the code as it echoes "else echo nothing here". When I apply the not (!) operator on isset, I get the expected result. It should ideal ...

Passing a Typescript object as a parameter in a function call

modifications: { babelSetup?: TransformationModifier<babel.Configuration>, } = {} While examining some code in a React project, I came across the above snippet that is passed as an argument to a function. As far as I can tell, the modifications p ...

Navigate to various parts of the page easily with a stationary navbar

After successfully implementing buttons to jump to different sections of my page using IDs like this: <button id="niftyBtn"><a href="#nifty">Things</a></button></br> <div id="nifty">Blah</div> I'm facing an ...

JavaScript tabs function malfunctioning upon page load

I attempted to implement tabs on my website using this example: http://www.w3schools.com/howto/howto_js_tabs.asp Although everything is functioning correctly, the default tab isn't opening as expected. The tab opens, but the header color does not get ...

Is it necessary to have a strong understanding of JavaScript in order to effectively utilize jQuery?

While I currently do not have knowledge of JavaScript, I am intending to acquire it soon. My query is whether a strong grasp of JavaScript is necessary to utilize jQuery effectively. I am already familiar with ActionScript and PHP, which share certain si ...

The lookat() function in three.js isn't functioning according to my requirements

Here is the code snippet I am working with: http://codepen.io/usf/pen/pGscf This is the specific section of interest: function animate() { //sun.rotation.x = t/1000; sun.rotation.y += 0.01; t += 0.1; earth.position.x = Math.sin((2*Ma ...

From JQuery to Vue.js: Transitioning to the Future of

Could someone assist me in converting this code into vue2js? I am new to using vue and could use some guidance. var $btnMenu = $('.menu-mobile'), $hideMenu = $('.hide-menu'); $btnMenu.on('click', function ...

List of values at the precise hour every day for 5 consecutive days

I'm currently dealing with an array that looks like this: 0 1 2 date 2000-06-01 10:00:00 0.040457 0.326594 0.492136 2000-06-01 11:00:00 0.279323 0.877446 0.464523 ...