Breaking down CSV rows and transforming numerical data (Typescript, Javascript)

Looking to convert a row from a csv file into an array and then transform the numeric values from string format.

This represents my csv file row:

const row = "TEXT,2020-06-04 06:16:34.479 UTC,179,0.629323";

My objective is to create this array (with the last two values in number format):

["TEXT","2020-06-04 06:16:34.479 UTC",179,0.629323]

I attempted this in three different ways, but did not achieve the desired outcome.

Attempt 1:

const array1 = row.split(",");

Outcome:

["TEXT","2020-06-04 06:16:34.479 UTC","179","0.629323"]

Attempt 2:

const array2 = row.split(",");
for (let element in array3){
    array3[element] = +array3[element];
}

Outcome:

[null,null,179,0.629323]

Attempt 3:

const array3 = row.split(",").map(x=>+x);

Outcome:

[null,null,179,0.629323]

Any assistance would be greatly appreciated!

Thank you!

Answer №1

Exploring the functionality of isNaN()

const data = "TEXT,2020-06-04 06:16:34.479 UTC,179,0.629323";

const dataArray = data.split(",").map(item => isNaN(item) ? item : +item)

console.log(dataArray)

Answer №2

When working with JavaScript, the inNan Function can be used to determine whether a number can be converted to Number.

Here is an example method you can try:

const row = "TEXT,2020-06-04 06:16:34.479 UTC,179,0.629323";
const array1 = row.split(",");
const newArray = array1.map(value => toNumber(value))
console.log("newArray", newArray)

function toNumber(value) {
    if(isNaN(value) || value === "")
        return value
    else 
        if(value.indexOf(".") === -1)
            return parseInt(value)
        else
            return parseFloat(value)
}

Another way to achieve this is by multiplying each value by 1:

let array = row.split(",").map(value => isNaN(value) ? value : value * 1);

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

How can I simulate pressing the ENTER key in Selenium without selecting any element?

Having trouble using the firefox selenium plugin and sending the enter key after pasting text? The ENTER key press should not interact with any other element on the page, just a simple 'dumb' ENTER key press. error [error] Element name=code not ...

Nested React Components in React Router Components

class AppRoutes extends Component { render () { return ( <Suspense fallback={<Spinner/>}> <Switch> <Route exact path="/" component={ HomePage } /> <Route exact path="/acti ...

Encountered an issue during my initial AJAX call

Hello everyone, I am currently attempting to use AJAX to send a request with a button trigger and display the response HTML file in a span area. However, I am encountering some issues and need help troubleshooting. Here is my code snippet: //ajax.php < ...

Unlock the Power of TWBS Ratchet: Manually Closing Modal Windows

Currently, I am in the process of developing a mobile web application using Ratchet. The main task at hand involves opening a modal, filling out a form, clicking a button to save the input data, and then closing the modal. Although I have managed to close ...

When does the ng-disable function become activated?

Here's an example: <button ng-disabled="!isSomethingValid() || loading || disabled" ... class="btn btn-primary"> What determines the condition for the ng-disable attribute to evaluate its expression? ...

Utilizing Firebase authentication to sign in via phone number in conjunction with Express on Node.js

Encountering an issue while implementing backend Firebase Authorization. After thoroughly reading the documentation (https://firebase.google.com/docs/auth/web/phone-auth), I came to understand that Authorization requires two steps: send phone send code ...

Prevent Float Filtering in AngularJS

As I work on creating a directive in AngularJs, I am facing an issue. The directive is supposed to receive a JSON object from the app controller and display its content accordingly. To better illustrate my problem, I have created a simple demo which can b ...

Is there a way to prevent prettier from automatically adding a new line when formatting HTML tags with ">"?

While navigating through the Prettier extension in Vscode, I am struggling to find a way to disable a specific scenario. In particular, I am having trouble with the formatting of an html tag. Below is a snippet of code that requires some adjustments whene ...

Removing double double quotes for Javascript

My problem involves a string that represents longitude/latitude in the format of dd°mm'ss''W (note 2 single quotes after ss). To convert this string into its decimal representation, I am using the following code snippet: function dmsTodeg ...

Selenium on Sauce Labs does not successfully load the page in Firefox after clicking

An issue has arisen where a test that functions properly with selenium webdriver locally is timing out when executed remotely on saucelabs.com. Notably, the test runs smoothly for Chrome in both local and remote scenarios. The problem seems to lie in the ...

Use a conditional statement for each element within the array

Below is the code I am currently using: if (res[0].toString() == "hello") { res[0] = "string"; }; While it works, I would like this logic to apply to all elements rather than just the first one. Is there a way to achieve this for every element in the ar ...

In the context of React Typescript, the term 'Component' is being mistakenly used as a type when it actually refers to a value. Perhaps you intended to use 'typeof Component' instead?

Looking to create a routes array and apply it to useRoutes in react-router@6. I am currently using TypeScript and Vite. However, I encountered an error when attempting to assign my component to the 'element' key. type HelloWorld = /unresolved/ ...

Creating a new service in Vue is a simple process that allows you to utilize powerful tools like this.$t and this.$alert

I've created a service file named message.vue <script> export default { methods:{ alert(msg,title){ this.$alertify.alert( title,msg); } } } </script> Here's how I use it: import me ...

Sharing code between a node.js server and browser with Typescript: A step-by-step guide

I have an exciting project in mind to develop a multiplayer javascript game using a node.js server (with socket.io) and I am looking for a way to share code, specifically classes, between the web client and the server. Luckily, I came across this resource: ...

Managing the output from a function: Tips and strategies

Below is the function I am currently working with: function kontrola(){ var jmeno = self.document.forms.newPassForm.user.value; $.get("checkMail.php?mail="+jmeno, function(data){ if(data=='1'){ alert('Tento ...

transmitting information to Laravel via ajax

Is it possible to send a multi-step form data separately to the Laravel controller in order to store them into MySQL? An example would be sending the inputs data shown below: <ul> <li> <input type="radio" class="step1r1" value ...

Exploration of mapping in Angular using the HttpClient's post

After much consideration, I decided to update some outdated Angular Http code to use HttpClient. The app used to rely on Promise-based code, which has now been mostly removed. Here's a snippet of my old Promise function: public getUser(profileId: nu ...

Creating a Dynamic Canvas Rendered to Fit Image Dimensions

I'm struggling with a piece of code that creates an SVG and then displays it on a canvas. Here is the Jsbin Link for reference: https://jsbin.com/lehajubihu/1/edit?html,output <!DOCTYPE html> <html> <head> <meta charset=&qu ...

Issue with Parcel / React 18 App.js failing to refresh cache

Currently, I am developing a React application for my school project. However, I have encountered an issue where certain components are not rendering in my App.js file. Strangely, when I place these components as child components of App.js, they do render ...

The deletion function necessitates a switch from a server component to a client component

I built an app using Next.js v13.4. Within the app, there is a server component where I fetch all users from the database and display them in individual cards. My goal is to add a delete button to each card, but whenever I try to attach an event listener t ...