I have a one-dimensional array of integer in JavaScript that I\'d like to add data from comma separated string, Is there a simple way to do this?
e.g : var strVale
All of the given answers so far create a possibly unexpected result for a string like ",1,0,-1,, ,,2"
:
",1,0,-1,, ,,2".split(",").map(Number).filter(x => !isNaN(x))
// [0, 1, 0, -1, 0, 0, 0, 2]
To solve this, I've come up with the following fix:
",1,0,-1,, ,,2".split(',').filter(x => x.trim() !== "").map(Number).filter(x => !isNaN(x))
// [1, 0, -1, 2]
Please note that due to
isNaN("") // false!
and
isNaN(" ") // false
we cannot combine both filter steps.