Transforming a string containing numerical arrays into their corresponding values

I'm currently tackling a coding task that involves receiving a text input from the user in a specific format like shown below:

value = "[1, 2, 3, 4]\n[9, 8, 7, 6]\n[1, 2, 3, 4]";

When using .split, the value is transformed into an array as follows:

value = ["[1, 2, 3, 4]", "[9, 8, 7, 6]", "[1, 2, 3, 4]"];

Now, the challenge is how to convert those strings back into actual arrays?

Answer №1

Utilize the combination of map and JSON.parse functions to process the split string:

var data = "[5, 6, 7, 8]\n[3, 9, 2, 5]\n[5, 6, 7, 8]";
data = data.split("\n");
var arraysData = data.map(d => JSON.parse(d));
console.log(arraysData);

Answer №2

Swap out the \ns for commas and wrap the input in [ and ]. This will create a JSON representation of one array containing 3 subarrays:

const value = "[1, 2, 3, 4]\n[9, 8, 7, 6]\n[1, 2, 3, 4]";
const json = '[' + value.replace(/\n/g, ',') + ']';
const arr = JSON.parse(json);
console.log(arr);

Answer №3

Just a single pair of square brackets stands between you and successfully parsing your data as JSON.


try {
    let list = JSON.parse('[' + data + ']');
} catch(error) {}

Using try/catch is wise when the input format may change unexpectedly.

Answer №4

After implementing the code as shown below:

value = ["[1, 2, 3, 4]", "[9, 8, 7, 6]", "[1, 2, 3, 4]"];

You can utilize this method to extract the actual arrays:

value.map(e => e.slice(1, -1).split(',').map(Number))

This approach will yield an array containing all your arrays.

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

Java program which inserts a character before a specific character

I've been exploring regular expressions and how to apply them in Java for the specific problem I'm trying to solve. My task is to insert a \ before every ". This is the code snippet I've written: public class TestExpressions { publ ...

Selecting JSONB keys in a case-insensitive manner in PostgreSQL (version 9.4 and newer)

Configuration (Using PostgreSQL 9.4+) Imagine a scenario where there is a table called product: create table product ( attributes jsonb ); and it contains the following data: insert into product (attributes) values ('{"Color": "Red"}'), ...

Issue with Express - Session not persisting across consecutive SSE requests

Currently, I am delving into Server-sent Events using Node.js and Express. I have successfully set up request handling and stream writing, but I am facing challenges with session management. The session does not persist between subsequent calls. Snippet o ...

Saving Backbone.js Collection as Text File on HDD & Re-importing Data

After experimenting with Backbone.js for a while, I've relied on localStorage to store most of my app data. However, I now want to explore the possibility of exporting my collection to plain text for easy backup purposes. Essentially, I envision a fea ...

Ways to update a single column in an HTML table when there is a change

I'm stuck trying to find a more efficient method for updating a column in an html table without having to reload the entire table. The table consists of player stats, all pulled from my MYSQL database and displayed in the table except for the last col ...

The server responded with an error code (406) Not Acceptable when attempting to Invoke-RestMethod using powershell.exe

After struggling to pass a parameter without receiving error 406 in Jenkinsfile, I finally managed to store the version id from a JSON response in a baseid variable. However, now I am stuck on how to use this baseid inside a PowerShell script as illustrate ...

Adjust the Material UI card to fill the maximum available height

I'm currently working with Material UI Card components. You can find more information here. My goal is to set a maximum height for these cards, ensuring that the text and images are displayed nicely. How should I approach this? Below is a snippet of ...

Guide on invoking a method from a class in a different file

Seeking a solution to a task involves calling a function from a different file within a class. Here's what I am trying to achieve: file1 export class Example { constructor() { ... } myCustomFunction = () => { ... } } file2 impor ...

Whenever I attempt to retrieve a div, I encounter an uncaught type error, specifically stating that it cannot read the property length of

As I work on integrating notifications into my rails app, I am closely following a tutorial available at Everything progresses smoothly until the point where I attempt to use JavaScript to fetch the notifications div and append notifications from a JSON E ...

I'm encountering the error message "Controller not a function, received undefined" even though I have not declared the controller globally

Encountering the same ERROR Argument 'AveragesCtrl' is not a function, got undefined. Despite attempting various solutions found on SO, I am still unable to resolve this issue. Any insights into what might be causing my error? <div > ...

What is causing my function to not wait for the resolution of the Promise?

checkout.ts updateGlobalValue(){ updateShadowDomButton(); let globalValue = fetchGlobalValue() } web_component_render.ts let globalValue; async fetchData() { let booleanFromApi = await callToExternalAPI(); return booleanFromApi; } functi ...

Tips for parsing JSON data from the IPGeoLocation API and incorporating it into a .chtml View

I'm attempting to create a code that retrieves data for a specific IP address, and I have utilized the Free IP GeoLocation API for this purpose. I have tried compiling a list of some data and attempted to deserialize it, but unfortunately, it returns ...

Place background image in the center with a background color overlay

After browsing through this post on Stack Overflow, I managed to stretch my background image using CSS with the background-size: cover; property. However, I realized that this solution doesn't completely meet my needs. I'm dealing with an image ...

Generating a Transform stream with ExcelJS to produce xlsx files

Currently, I am utilizing the ExcelJS module and creating a wrapper to suit my specific needs. This wrapper implements the Transform Stream API, and surprisingly, the node version being used is 0.10.40. The ExcelJS module offers a stream API, and based on ...

Exploring deeply nested arrays of objects until a specific condition is satisfied

My array is structured in a nested format as shown below. const tree = { "id": 1, "name": "mainOrgName", "children": [ { "id": 10, "name": "East Region", "children": [ ...

Select multiple options by checking checkboxes in each row using React

Is it possible to display multiple select checkboxes with more than one per row? For example, I have four options [a, b, c, d]. How can I arrange it to have 2 options per row, totaling 2 rows instead of having 1 option per row for 4 rows? ☑a ☑b ☑c ...

Unconventional way of assigning class properties in Typescript (Javascript): '?='

Recently, I came across the ?= assignment expression within a class property declaration. Can anyone provide some insight into what this means? I am familiar with the new Optional Chaining feature (object?.prop), but this particular syntax is unfamiliar t ...

PHP Curl - A guide on sending a POST request with parameters formatted in JSON within the request body

I am looking to recreate a POST request using PHP curl. The request parameters need to be formatted as JSON in the body and the response will also be in JSON format. { "api_key": "scTrCT", "test": "true", "service_provider_list": [ { "facili ...

Combining two arrays into a unified JSON/array in a Node.js environment

In my Node application, I am working with 2 arrays. ['3', '7' ] [ 'Circulatory and Cardiovascular', 'Respiratory' ] My goal is to generate the following result. {{"id": "3","name":"Circulatory and Cardiovascula ...

Navigation menu with submenus containing buttons

I attempted to incorporate a dropdown into my existing navigation bar, but unfortunately, the dropdown content disappeared after adding the necessary code. I am now at a loss on how to troubleshoot this issue and make the dropdown function properly. Despit ...