b.herring
b.herring

Reputation: 643

convert string array into array of strings

In javascript I currently have: "[11,8,7,6,5,4]"

I would like the convert this into ["11", "8", "7", "6", "5", "4"]. I've tried using .split() on the string but it is not returning the desired result, along with any other attempts. Thanks

Upvotes: 0

Views: 122

Answers (6)

var obj = JSON.parse("[11,8,7,6,5,4]");
var out=obj.map(String);
console.log(out);
  1. Parse the data with JSON.parse(), and the data becomes a JavaScript object. (https://www.w3schools.com/js/js_json_parse.asp)

  2. .map function is like apply function of python or R, which acts on each element of the incoming array using the function defined within the parentheses; i.e. The map() method creates a new array with the results of calling a function for every array element. (https://www.w3schools.com/jsref/jsref_map.asp)

Upvotes: 0

Mohit G.
Mohit G.

Reputation: 86

  • Parsing a string will convert it in an array.
  • Later then you can map each element of array to be a String, then you will have Array Of Strings

let array = JSON.parse("[11,8,7,6,5,4]");
let arrayOfStrings = array.map(item => `${item}`);

console.log('array', array);
console.log('arrayOfStrings', arrayOfStrings);

PS: I've used arrow functions, you might switch to basic functional syntax.

Upvotes: 0

demkovych
demkovych

Reputation: 8817

The fastest way: (Updated)

JSON.parse("[11,8,7,6,5,4]").map(String)

Upvotes: 5

SuperColin
SuperColin

Reputation: 151

You could use a for loop to convert them into strings if that's all you want:

for(num of numArray){
num = num.toString();
}

Upvotes: 0

Bilal Siddiqui
Bilal Siddiqui

Reputation: 3629

Seems you are looking for this:

console.log(eval("[11,8,7,6,5,4]").map(String))

Upvotes: 0

Rajneesh
Rajneesh

Reputation: 5308

By making use of match method of string and this regex /\d+/g, will get you the expected output.

var string = "[11,8,7,6,5,4]";

var result = string.match(/\d+/g);

console.log(result);

Upvotes: 2

Related Questions