Changing a multi-line string of numbers into a double array using javascript

I have a matrix of strings that looks like this:

stringMatrix = `
1 0 0
0 1 0
0 0 0
`

I am looking for a way to convert it into a double array: [[1,0,0], [0,1,0], [0,0,1]], is there a more elegant js-y solution to achieve this?

I attempted

matrix = values[0].trim().split('\n');
, but it only separates the outer layer into: ["1 0 0", "0 1 0", "0 0 0"]; I could use a for-loop, but I was hoping for a solution involving lambda expressions or fat arrows.

//plain vanilla javascript

Answer №1

One of the easiest ways is to simply split and then map it.

let stringMatrix = `
1 0 0
0 1 0
0 0 0
`

let result = stringMatrix.trim().split("\n").map( line => line.split(/\s+/).map(Number))

console.log(result)

Answer №2

This code snippet will generate a number array as an output by utilizing the split and map functions to process a string matrix containing numerical values.

stringMatrix = `
1 0 0
0 1 0
0 0 0
`;
let result = [];
stringMatrix = stringMatrix.trim().split('\n').map(function(element){
    let ret = [];

    for(let digit of element.match(/\d/g)){
        ret.push(parseInt(digit));
    }
    return ret;
});


console.log(stringMatrix);

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 is the best way to expand the width of a table cell in a React + Material project?

Currently, I am utilizing material UI in conjunction with React to display my data in a table format. Within the table, there are specific titles such as "GENERAL_INFORMATION" and "INFORMATION" that I intend to center align. However, I have encountered an ...

Developing a Monitoring-Frontend Application with backbone.js

I am in the process of developing a tool for monitoring and analyzing statistics. The current setup is as follows: Collector-Backend: This component receives queries in JSON format from the frontend, fetches and stores them in a cache, and then notifies ...

Ways to minimize renders while toggling a checkbox

I'm currently working on developing a high-performance checkbox tree component. To manage the checked checkboxes, I am utilizing a parent level state that contains an array of selected checkbox IDs => const [selected, setSelected] = useState([]); ...

I'm having trouble with AngularJS routes not functioning properly when accessed directly. I am using html5 mode in conjunction with

When accessing URLs directly in my Angular app either through the address bar or from external links, all routes default back to the home page. However, when navigating within the app, routes work as expected. I have come across similar issues on Stack Ov ...

Show only the present y-coordinate in the ToolTip of a chart.js

I am currently working on developing a chart using Chart.js, and my goal is to only show the y-axis value in the tooltip. The current display shows: date name_of_line: measurement example: Jan 1, 2020, 8:00:00 AM 5th Percentile: 100 oz. However, I would ...

Resolving the bothersome complications of self-looping steps in jQuery animate delay

My timeline definition includes selectors and a sequence of delays and animations to apply to an object. I have also provided the option to loop through the steps for a specific object. Here is the function that I use to queue the animations: function an ...

Steps for adding a row as the penultimate row in a table

There aren't many solutions out there that don't rely on jQuery, but I'm looking to avoid it. The row content needs to be generated dynamically. Here is my flawed approach: function addRow() { let newRow = '<tr><td>B ...

Ways to implement material-ui button design on an HTML-native button

I am using pure-react-carousel which provides me an unstyled HTML button (ButtonBack). I would like to customize its style using material-ui. Trying to nest buttons within buttons is considered not allowed. An approach that works is manually assigning th ...

Unusual escape_javascript quirk witnessed in Ruby on Rails

Once the ajax method is called, the escape_javascript function starts outputting </div> </div> </div> for each rendered item. Despite thoroughly checking all closing tags multiple times, I can't seem to identify any errors. Could thi ...

Challenges with ColdFusion's floating point calculations

I am encountering an issue with my program where it is not displaying two decimal points properly. For example, when I enter 140.00, it shows as 140.0. Strangely, if I enter 140.15, it displays correctly as 140.15. It seems to consistently drop the zero. B ...

Instructions for selecting a checkbox using boolean values

According to the HTML specification, you should use the checked attribute in the <input type="checkbox"> tag to indicate that it is checked. However, I only have a boolean value of either true or false. Unfortunately, I am unable to manipulate the b ...

Malfunctioning Bootstrap collapse feature

I am experiencing an issue with my modal that contains 2 blocks. When I click on the .emailInbound checkbox, it opens the .in-serv-container, but when I click on the .accordion-heading to reveal the comment section, the .in-serv-container collapses. What c ...

Updating the time and date format within an AngularJS application

I am receiving date and time data from the API and would like to adjust the format. The current format is "2016-05-12", "07:17:35". Desired format: 12-May-2016 7:30 PM: <table class="table"> <thead> <tr> <th& ...

How to visually represent options without labels using icons in Material UI Autocomplete

My options are structured as follows: const options = ['option1', 'option2']; I am looking to display the options with icons like this: https://i.stack.imgur.com/aubHS.png The current code for rendering options looks like this: ...

Difficulty occurred when trying to import Polymer components

Currently, I am in the process of learning how to utilize Polymer. I meticulously followed the instructions provided exactly as specified here. However, upon reaching step 3 and adding the import for paper-checkbox, an error presented itself: Error: A c ...

Picture is unavailable for viewing - (Express, Pugjs)

I'm having trouble getting an image to display on my page using a pug template. Despite following the setup and files correctly, the image still isn't showing up. Here is what I have: index.js app.use('/images', express.static(path.r ...

Tips for sending event and additional arguments to a click handler

Hi there, I recently created a canvas using easelJS. Within my canvas, I have points that have a click handler defined for them with this syntax: p.on("click", handleMouseClickEvent); However, I am facing an issue when trying to pass arguments to the han ...

How to dynamically change the class of an element that contains other elements using JavaScript and JQuery

I have created a blog archive with the following format: +Year +Month Title Here is a snippet of the code: <ul> <span class="toggle">+</span> <li class="year">$year <ul> <span ...

Which is the best choice for a large-scale production app: caret, tilde, or a fixed package.json

I am currently managing a sizeable react application in production and I find myself undecided on whether it is more beneficial to use fixed versions for my packages. Some suggest that using the caret (^) is a safer route, but I worry that this could poten ...

The `Target closed` error in Playwright Library is triggered solely by the closing of either the `context` or `browser`

The code snippet below showcases a Node.js script that leverages the Playwright Library for browser automation (not Playwright Test) to extract data from a local website and display the results in the terminal. The challenge arises when the script encounte ...