Split csv row and convert numeric values (Typescript, Javascript)

1.2k Views Asked by At

I'm trying to convert a csv file row to an array, and then convert the numeric values from string.

This is my csv file row:

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

And this my goal array (last two numeric values without string format):

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

I have tried in three differente modes, but I don´t get the goal result.

Try 1:

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

Result:

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

Try 2:

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

Result:

[null,null,179,0.629323]

Try 3:

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

Result:

[null,null,179,0.629323]

Can someone help me?

Thanks!

2

There are 2 best solutions below

0
On BEST ANSWER

Using isNaN()

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

const array = row.split(",").map(i => isNaN(i) ? i : +i)

console.log(array)

1
On

inNan Function in JS check wether number can be converted to Number.

Give it a try following method

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)
}

One another way to accomplish this to multiple value by 1.

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