Convert integer array to string array in JavaScript
I have an array like below:
var sphValues = [1, 2, 3, 4, 5];
then I need to convert above array like as below one:
var sphValues = ['1', '2', '3', '4', '5'];
How can I convert? I used this for auto-complete.
You can use map and pass the String constructor as a function, which will turn each number into a string:
sphValues.map(String) //=> ['1','2','3','4','5']
This will not mutate sphValues. It will return a new array.
Use Array.map
:
var arr = [1,2,3,4,5];
var strArr = arr.map(function(e){return e.toString()});
console.log(strArr); //["1", "2", "3", "4", "5"]
Edit:
Better to use arr.map(String);
as @elclanrs mentioned in the comments.
just by using array methods
var sphValues = [1,2,3,4,5]; // [1,2,3,4,5]
sphValues.join().split(',') // ["1", "2", "3", "4", "5"]
for(var i = 0; i < sphValues.length; i += 1){
sphValues[i] = '' + sphValues[i];
}
Use .map()
at this context that is a better move, as well as you can do like the below code this would add more readability to your code,
sphValues.map(convertAsString);
function convertAsString(val) {
return val.toString();
}