Guide to converting numerous lines of numbers into an array using JavaScript

I have a large collection of numbers that I need to convert into an array:

142156
108763
77236
78186
110145
126414
115436
133275
132634
......
82606

Is there a way to assign all these numbers to a variable and then convert it into an array? I'm considering using RegExp or converting to a string first. Any suggestions on how to approach this?

Answer №1

Parse a string from a file, then divide the string at every line break and convert the resulting array of strings into numbers.

const text = `142156
108763
77236
78186
110145
126414
115436
133275
132634`;

const numbers = text.split(/\r?\n/).map(Number)

console.log(numbers)

Answer №2

One way to achieve this task is by using the code snippet below:

const nums = document.getElementById("numbersDiv").innerHTML;

const numsToArr = nums.split('\n').map(Number)

console.log({ numsToArr } )
<div id="numbersDiv">142156
108763
77236
78186
110145
126414
115436
133275
132634</div>

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

Utilizing 'Ng-If' causes a glitch in the program during the execution of a $( '#x' ).change event or when adding a new item with AngularFire $add

After implementing ng-if in my code, I observed two specific instances where it caused unexpected behavior. The first instance involves using ng-if="isOwnProfile" for an image-upload toolbar. However, the use of ng-if resulted in the event listener ceasin ...

Karma jasmine and an angular controller that utilizes the 'Controller as' syntax (where 'this' is used instead of $scope)

I'm having trouble setting up karma for my unit tests, specifically on a basic example: Here is the controller file: angular.module('balrogApp.requests', [ /* Dependencies */ ]) // Routes configuration .config(['$routeProvider&a ...

"Resolving the problem of populating an empty array with JSON

My JSON structure at the top level is set up like this: { "video": [], "messages": [], "notifications": [] } In the database output stored in a variable called "result," I have data that I want to add to the "vide ...

Can you explain the significance of `Component<Props>` in React Native?

Recently, I started a new react-native project and noticed a change in the component syntax. It now reads export default class WelcomeScreen extends Component<Props>, which is different from what it used to be, export default class WelcomeScreen exte ...

Obtain a zero total through MongoDB's aggregation feature

Can you assist me with aggregate functions in Mongo? Here is my current aggregation code: const likes = await this.aggregate([ { $match: { post: postId }, }, { $group: { _id: '$likeType', count: { $sum: 1 }, }, }, ...

Close any open alerts using Protractor

While using protractor and cucumber, I have encountered an issue where some tests may result in displaying an alert box. In order to handle this, I want to check for the presence of an alert box at the start of each test and close/dismiss it if it exists. ...

The React Swiper.js slider functions properly only when the page is resized

After implementing Slider.js React, I encountered an issue where the slider only functions properly after resizing the page. Clicking on the next button does trigger a console log for onSlideChange event, but it does not actually move to the next slide. An ...

How can you call a function in JavaScript based on a condition?

Is there a way to conditionally truncate text using a function called Truncate only when the offsetHeight of the left div with class demo is greater than the offsetHeight of the right div? If this condition is not met, then simply return the original conte ...

Error: Code cannot be executed because the variable "sel" has not been defined in the HTML element

Every time I try to click on the div, I encounter an error message stating 'Uncaught ReferenceError: sel is not defined at HTMLDivElement.onclick' I am currently developing with Angular 8 and this error keeps popping up. I have read through simil ...

Retrieve a JSON object from a Knockout observable array using the object's ID

I'm struggling to find examples of ko.observablearrays that deal with complex JSON objects instead of simple strings. I have an observable array containing a large JSON object with several properties, and I need to retrieve a specific object based on ...

JQuery is blocking the submission of an HTML form

During my exploration of an AJAX/JQuery tutorial for a registration script that interacts with PHP/MySQL and is submitted via JQuery, I encountered a recurring issue. The problem lies in the form submitting directly to the action page instead of its intend ...

Adding items to an array within a jQuery each loop and performing a jQuery ajax request

I am trying to loop through an array, push the results into a JavaScript array, and then access the data outside of each loop and AJAX call. Can anyone explain how to do this? This is what I have attempted: var ides = ["2254365", "2255017", "2254288", ...

Sending data from TextBoxFor to controller with @Ajax.ActionLink in MVC

I’ve gone through numerous questions dealing with the same issue, yet none of them seem to solve my problem (or I’m completely missing the point). As the title suggests, I am attempting to transfer the value from a TextBoxFor to my controller using an ...

Is it possible to reverse engineer a UI by starting from its current state and debugging backwards?

When it comes to web development, users often provide screenshots of their "invalid state". Using React, I had a thought about debugging in a different way: starting from the current state: A user sends us a screenshot of an invalid UI state. We use dev ...

Sequencing and fulfillment of promises in a job queue using Promise.race

Currently, I'm grappling with the concepts of job queue and promise resolution in Javascript. While going through Nicholas Zakas' book "Understanding ECMAScript 6", I came across a code snippet regarding Promise.race() that has left me puzzled: ...

JavaScript Challenge: Calculate the Number of Visible Characters in a Div

I have a div with text content (a string of length S) that is fixed in size but can be of any length. When the text exceeds a certain point (referred to as L), it gets truncated, and the portion beyond that limit becomes invisible. In other words, characte ...

Tips for implementing async await properly within a function array that contains two functions for utilizing Promise.all in Vue

I am facing an issue with using await at the specified location in 1.vue file. Whenever I try to use await, it throws an error stating Unexpected reserved word 'await'. How can I modify async useFunctionToAllServers() to execute sequentially afte ...

Exploring Grails Assets, Redirections, Secure Sockets Layer, and Chrome

Using Grails 2.1.1 with the resources plugin, I have encountered an issue when incorporating the jstree library which comes with themes configuration: "themes":{ "theme":"default", "dots":false, "icons":true } The JavaScript in the library locat ...

Determine whether a request is for CSS or JavaScript when using NodeJS and Express

My routing configuration includes the following setup: app.get('*', function (req, res, next) { req.xhr ? next() : res.render('layout/layout'); }); The idea behind this is to return the base layout if the request is not an XMLHttp ...

Add CSS styles directly into the shadow-root instead of the head tag | Vue.js and Webpack

Currently, I'm developing a widget that can be embedded on websites using Vue.js along with vue-custom-element. Everything was going well until I encountered an issue. The problem arises when trying to integrate a component (along with its CSS) from ...