I have an array of strings.
a = ['1', 'car', '2'];
I want to parse only the parsable elements, my objective is:
a = [1, 'car', 2];
How can I do that? What does it happen when I try to parse a[1] ?
I have an array of strings.
a = ['1', 'car', '2'];
I want to parse only the parsable elements, my objective is:
a = [1, 'car', 2];
How can I do that? What does it happen when I try to parse a[1] ?
Try
a.map(function(x) { return +x || x; })
+x
will try to convert the value to a number, and return NaN
if it fails. That is falsy, and cause the RHS of the ||
to be evaluated, returning the original value.
However, this will fail on '0'
, so you need to do
a.map(function(x) { return isNaN(x) ? x : +x; }
It's a bit more compact in ES6 environments:
a.map(x => isNaN(x) ? x : +x);
Since the purpose of the question has become more clear now, an edit:
var a = ["1", 'car', 2];
a = a.map(function(element) {
//check if element is a number and not NaN or empty string
if (!isNaN(element) && element != "") {
return parseInt(element, 10);
}
else
{
return element;
}
});
document.body.textContent = a;
This will traverse your array. Testing if the array element is a number, if so transform the number if possible. I'm using Array.prototype.map
for this. Please note that this only filters integers. If you want to filter floats use parseFloat
. That will parse integers and floats.
For this you have to loop for each value and check the parse int or not. Here is sample example and create another array.
var count_a = {};
for(var i=0; i<a.length;i++)
{
if (!isNaN(a[i]))
{
count_a[i] = parseInt(a[i], 10);
}
else { count_a[i] = a[i] }
}
a = count_a
or as first link below you can try this. whenever you want to use of array element.
var a = ['1','2','3'];
var result = a.map(function (x) {
return parseInt(x, 10);
});
How to convert all elements in an array to integer in JavaScript?
Array construction:
a[0] = 1;
a[1] = 'car';
a[2] = 2;
You need an indexed array.