Import data from a file into a JavaScript 2D array

Looking for a way to load an array from a text file in JavaScript? Here's what I have:

var linePoints = [[0, 3], [4, 8], [8, 5], [12, 13]];

But rather than defining it in the code, I'd like to read it from a text file. The file looks like this:

input.txt:

0 3
4 8
8 5
12 13

I came across this post on Stack Overflow, which discusses something similar but for a 1D array. I'm wondering if there's a special function that can be used for a 2D array. In Java, I would read each line and then split it, but as a newcomer to JavaScript, I'm not sure how to approach this task.

Answer №1

Here is a solution that should meet your needs:

$.get("file.txt", function(data) {
      var items = data.split("\r\n").map(function(el){ return el.split(" ");});
  });

Check out this live example: http://example.com

Answer №2

It's important to take into account various newline formats and ensure that the array contains numbers, not strings.

Here's a suggestion for the code:

$.get("textFile.txt", function(data) {
    var items = data.split(/\r?\n/).map( pair => pair.split(/\s+/).map(Number) );
});

Answer №3

There isn't a pre-existing function specifically designed for parsing input in the exact way you desire. However, an alternative approach would be to utilize the String.split() method, which can segment a string into multiple smaller strings based on a specified delimiter:

let example = "Hello World";
let result = example.split(" "); // split based on blank space
console.log(result); // ["Hello", "World"]

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

Specializing function templates for arrays in C++ involves creating specific implementations that are

I attempted to create a function that could manipulate a series of data. //For stl containers template<typename T> void foo(T x){ for(auto iter=x.begin();iter!=x.end();++iter) do_something(*iter); } While this function worked well for S ...

Access remote web page within bootstrap modal

Dealing with a recurring issue, I am trying to create a modal that opens content from a remote page populated by a MySql database. Custom styling is also required for the modal. Progress has been made, but now I'm stuck. Below is the current code: Ou ...

Does getServerSideProps execute for each page request, or solely for HTTP requests?

Does getServerSideProps execute with every page request, or is it specifically for HTTP requests? ...

Error: Async API Call Triggering Invalid Hook Invocation

When working with my functional component, I encountered an issue while trying to implement a react hook like useMemo or useEffect. It seems that the error may be caused by the asynchronous nature of the API call. In the service file: export const getData ...

The function is not being called by ngModelController $parsers in Angular version 1.4.7

I'm encountering an issue with ngModel.NgModelController.$parsers. Let me explain with an example: I have created a directive for an input field. Whenever I change the value in this input in the HTML, it should call my specified function. The registe ...

Fade out the jQuery message after a brief 2-second pause

In my Rails application, I encountered an issue with a flash message that appears after successfully completing an AJAX action. The message displays "Patient Added" but does not include a way to close it without refreshing the page. To address this, I atte ...

React Native package identifies a primary module for handling HTTPS requests

For my latest project, I decided to experiment with incorporating HTTPS. I began by creating a new project using expo init test and then installed the HTTPS library with npm install https. Next, I made edits to App.js by adding the following line at the t ...

Update WooCommerce Mini-cart with ajax refresh

I'm having an issue with my custom plugin where everything is working properly, except for the fact that the mini cart is not updating after adding items. I have tried various methods to trigger a refresh, but so far nothing has worked. Below is a sni ...

Retrieve a list of JSON data using the Python requests library

Utilizing the python request module, I am retrieving JSON responses from 3 different servers. The structure of the 2 JSON response are as follows: JSON Response 1: {"MaleName1":"John","MaleAge1":"1.40531900","FemaleName1":"Anna","FemaleAge1":"14"} JSON ...

What is the best method for communicating between windows in an electron application?

As I embark on the journey of creating my first electron app, I kindly ask for your understanding :) Upon clicking a button in the main Window, a new window should open displaying a JSON string. This action is captured by ipcMain: ipcMain.on("JSON:ShowPa ...

Tips for creating an input box that only accepts floating point numbers:

I have a custom component - a text box that I am using in two different places. In one location, it accepts integers and in another, floats. For the integer validation (where dataType=2), I have successfully implemented it. However, for the float validat ...

I was confused about the distinction between the https.get() and https.request() functions in the Node.js npm package for https

// # Exciting Nodejs Programs! const https = require('https'); https.get('https://www.google.com/', (res) => { console.log('statusCode:', res.statusCode); console.log('headers:', res.headers); res.on ...

Looking for a specific phrase in the data entered by the user

I am dealing with data in ckeditor that looks like this: <p>test 1</p> <p>test 2</p> <p><img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICw ...

Rendering JSON Data in JavaScript using Table Pagination

Currently, I am working on rendering JSON data from a URL onto a table. My challenge is to display only 10 rows per page and I'm seeking guidance on how to achieve this. Below is the code snippet that I am using for rendering the data: const url = " ...

Uploading Massive Form Data Using Angular JS

After spending countless hours on this project, I still can't figure out how to post data into a table using JavaScript objects. While I can easily work with smaller data sets, I'm struggling with handling multiple nested objects. EDIT: ...

Oops! There was a validation error as the duration was not formatted as a number. Please make sure to provide a valid numerical value for the duration field

When attempting to update data from a MongoDB database and checking the results on Postman, an error is encountered. The error reads as follows: "Error: ValidationError: duration: Cast to Number failed for value \"NaN\" at path \"duration&bs ...

The white-spaces in Quill JS do not retain their original formatting

I recently integrated Quill JS editor into my website. During testing, I noticed that any text inputted after a white space gets emitted when alerting the content. Below is the HTML code snippet: <div id="postCommentEditor" class="postCo ...

Is it possible to pass an array to a class constructor in JavaScript using destructuring?

I am interested in developing a Statistics class that can handle 25 inputs (or possibly more or less) and perform calculations to find values such as mean, median, mode, range, variance, and standard deviation. Is it possible to achieve something like thi ...

Trackball's controls are not responding correctly

Recently, I have been using trackball controls and I've come across a strange bug. When I pan and then zoom out from my new position, the controls start to behave erratically, pulling towards the origin (the further I pan, the worse the issue becomes) ...

Issue with retrieving data from MySQL database using PHP in Chart.js

I am currently facing an issue while trying to populate a chart using the ChartJS plugin with data from my MySQL database. I keep encountering the error message: mysqli_fetch_assoc(): Couldn't fetch mysqli_result in ... Despite using json_encode, ...