Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 957
gihansalith Avatar asked Oct 29 '14 06:10

gihansalith


People also ask

How do you convert a number array to a string array?

To convert an array of numbers to an array of strings, call the map() method on the array, and on each iteration, convert the number to a string. The map method will return a new array containing only strings.

How do you convert a string of numbers to an array of numbers JS?

To convert an array of strings to an array of numbers:Use the forEach() method to iterate over the strings array. On each iteration, convert the string to a number and push it to the numbers array.

How do I convert a string to an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


1 Answers

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.

like image 157
elclanrs Avatar answered Sep 30 '22 17:09

elclanrs