CAN YOU CONVERT A LIST TO AN ARRAY?

Not the answer you’re looking for? Browse other questions tagged javascript arrays string deserialization or ask your own question.

Bạn đang xem: Can you convert a list to an array?


; alert(array);

In this case, alert would pop-up a 0,1. When it would be an array, it would pop-up a 0, & when alert(array); is called, it should pop-up the 1.

Bạn sẽ xem: Convert menu string lớn array javascript

Is there any chance khổng lồ convert such string into a JavaScript array?

Depending why you want this, strings & arrays are already very similiar (i.e. String === ‘0’ in your question), in most cases you can treat a string as an array of chars và use array methods on it. – Paul S. Nov 7 “12 at 15:19 PaulS.: That will fail in IE8 và lower. – I Hate Lazy Nov 7 “12 at 16:00 possible duplicate of convert javascript comma separated string into an array – Baby Apr 8 “14 at 3:57 Best practice for tư vấn all types of strings. See here darkedeneurope.com/a/32657055/2632619 – Andi AR Sep 18 “15 at 16:43

For simple array members like that, you can use JSON.parse.

var array = JSON.parse(“”);

This gives you an Array of numbers.

If you use .split(), you”ll kết thúc up with an Array of strings.

Just be aware that JSON.parse will limit you to lớn the supported data types. If you need values like undefined or functions, you”d need to lớn use eval(), or a JavaScript parser.

If you want to lớn use .split(), but you also want an Array of Numbers, you could use Array.prototype.map, though you”d need to shim it for IE8 và lower or just write a traditional loop.

var array = string.split(“,”).map(Number); tóm tắt Follow edited Nov 7 “12 at 15:19 answered Nov 7 “12 at 15:08 I Hate LazyI Hate Lazy 42.7k 10 10 gold badges 80 80 silver badges 74 74 bronze badges 11 6 Also be aware that JSON.parse(); is not available in IE6, IE7. I think in this case the String.split(‘,’); is easier. – scunliffe Nov 7 “12 at 15:15 scunliffe: True, a shim would be needed, or one could take the jQuery approach khổng lồ shim it var array = (new Function(“return ;”))(). Using .split() is alright if Numbers aren’t needed, otherwise you’d need to maps the result. – I Hate Lazy Nov 7 “12 at 15:18 12 Downvoter: Try to lớn describe what is wrong with the answer so that I can demonstrate how you’re wrong. – I Hate Lazy Nov 7 “12 at 15:59 I Hate Lazy This doesnt tư vấn object string.see here darkedeneurope.com/a/32657055/2632619 – Andi AR Sep 18 “15 at 16:41 FarzadYZ Be careful with that (using eval). If the array contains values from client side input đầu vào this will be insecure. – Wilt May 9 “16 at 12:01  | Show 6 more comments 133

Split it on the , character;

var string = “0,1”; var array = string.split(“,”); alert(array); chia sẻ Follow answered Nov 7 “12 at 15:08 Alex K.Alex K. 158k 29 29 gold badges 242 242 silver badges 266 266 bronze badges địa chỉ cửa hàng a phản hồi | 89

This is easily achieved in ES6;

You can convert strings to lớn Arrays with Array.from(“string”);

Array.from(“01”)

will console.log

Which is exactly what you”re looking for.

Share Follow edited Feb 4 “18 at 16:53 Kip 98.3k 82 82 gold badges 222 222 silver badges 257 257 bronze badges answered Jun 28 “16 at 3:27 Ray KimRay Kim 1,638 11 11 silver badges 24 24 bronze badges 8 1 This is awesome. I moved my code from JSON.parse khổng lồ Array.from as am using ES6. Thank you Ray Kim – Eshwar Prasad Yaddanapudi Sep 27 “16 at 7:49 console.log(typeof Data); //string ========== var myArray = Array.from(Data); ============ console.log(typeof myArray); //Object doesn’t tư vấn property or method ‘from’ ========== Why Is that? – Janatbek Sharsheyev Feb 17 “17 at 22:19 1 But Array.from(“0, 1, 233”) will return , what if I want ? – Tina Chen Jun đôi mươi “17 at 7:04 21 This is converting every single character as an array element. But we need only comma separated strings to lớn be array elements. So not a valid solution. – Edison D’souza Sep 28 “17 at 7:23 1 This method is only reliable when argument is a mix of strings. – Josh Habdas Oct 25 “19 at 6:14  | Show 3 more comments 62

If the string is already in list format, you can use the JSON.parse:

var a = “”; a = a.replace(/”/g, “””); a = JSON.parse(a); cốt truyện Follow answered Sep 5 “15 at 19:27 otaviodecamposotaviodecampos 981 8 8 silver badges 8 8 bronze badges 0 add a comment | 26

Convert all type of strings

var array = (new Function(“return ;”)()); var string = “0,1”; var objectstring = “, , “; var stringArray = (new Function(“return ;”)()); var objectStringArray = (new Function(“return ;”)());

JSFiddle https://jsfiddle.net/7ne9L4Lj/1/

Result in console


*

Some practice doesnt support object strings

– JSON.parse(“”); // throw error – string.split(“,”) // unexpected result share Follow edited Nov 1 “18 at 7:15 answered Sep 18 “15 at 16:40 Andi ARAndi AR 2,118 1 1 gold badge 20 20 silver badges 25 25 bronze badges 2 Great function I also use it but unfortunately it does NOT work for strings or symbols: like e.g. “0,s” any ideas how to lớn fix that? – sqp_125 Aug 31 “17 at 12:48 1 sqp_125 try 0,’s’ ? – Unreality Nov 23 “17 at 6:28 showroom a comment | 21

For simple array members like that, you can use JSON.parse.

var listValues = “”; var array = JSON.parse(“”);

This gives you an Array of numbers.

Xem thêm: Releases · 133Spider/Aqlite · Github, Lag Fixer For Pub G Lite 120Fps

now you variable value is like array.length=1

Value output

array.ComplianceTaskID array.RequirementTypeID array.MissedRequirement array.TimeOverdueInMinutes tóm tắt Follow answered Jul 10 “13 at 3:51 Raghav ChaubeyRaghav Chaubey 211 2 2 silver badges 2 2 bronze badges add a phản hồi | 17

Another option using the ES6 is using Spread syntax.

var convertedArray = ;

var stringToConvert = “012”; var convertedArray = ; console.log(convertedArray); giới thiệu Follow answered Feb 17 “17 at 5:28 Abhinav GalodhaAbhinav Galodha 7,630 2 2 gold badges 26 26 silver badges 37 37 bronze badges 1 2 Awesome! Along with Array.from answer they should be the only answers for ES6 solutions. – Artyom Pranovich Jun 2 “17 at 8:42 địa chỉ cửa hàng a comment | 17

You can use split

Reference: http://www.w3schools.com/jsref/jsref_split.asp

“0,1”.split(“,”)

Share Follow edited Sep 17 “17 at 13:59 Akash Joshi 560 4 4 silver badges 15 15 bronze badges answered Nov 7 “12 at 15:09 dm03514dm03514 50.1k 16 16 gold badges 96 96 silver badges 130 130 bronze badges 0 showroom a phản hồi | 10

use the built-in maps function with an anonymous function, like so:

string.split(“,”).map(function(n) );

here”s how you would use it

var string = “0,1”; var array = string.split(“,”).map(function(n) ); alert( array ); giới thiệu Follow edited Mar 9 “16 at 21:54 answered Sep 24 “14 at 22:07 Dan MantylaDan Mantyla 1,648 đôi mươi 20 silver badges 32 32 bronze badges 4 1 This is the most generally applicable answer. JSON can not be used for arbitrary delimiters (e.g. Tab, space, etc) – StephenBoesch Feb 2 “16 at 23:33 This won’t work when your array values are string values that possible have a comma inside. For example: “123, ‘a string with a , comma’, 456”. You could use a more complex regex to handle such cases correctly (for example something lượt thích suggested here). – Wilt May 9 “16 at 12:06 Wilt well no it wouldn’t, but yeah you could use regex to fix that – Dan Mantyla Feb 14 “18 at 20:21 2 I didn’t mean lớn criticize your answer, but I wrote this because I used your solution and ran into this issue myself. Thought of leaving the bình luận for others possibly running into similar problems. – Wilt Feb 15 “18 at 17:53 add a phản hồi | 3

More “Try it Yourself” examples below.

Definition and Usage The split() method is used to lớn split a string into an array of substrings, and returns the new array.

Tip: If an empty string (“”) is used as the separator, the string is split between each character.

Note: The split() method does not change the original string.

var res = str.split(“,”); nói qua Follow answered May 16 “18 at 7:13 HAROONMINDHAROONMIND 93 7 7 bronze badges showroom a bình luận | 3

You can use javascript Spread Syntax to lớn convert string to an array. In the solution below, I remove the comma then convert the string khổng lồ an array.

var string = “0,1” var array = console.log(array) mô tả Follow answered Dec 3 “19 at 18:34 p8ulp8ul 1,044 11 11 silver badges 13 13 bronze badges showroom a bình luận | 2

How to lớn Convert Comma Separated String into an Array in JavaScript?

var string = “hello, world, test, test2, rummy, words”; var arr = string.split(“, “); // split string on comma space console.log( arr ); //Output

For More Examples of convert string khổng lồ array in javascript using the below ways:

Split() – No Separator:

Split() – Empty String Separator:

Split() – Separator at Beginning/End:

Regular Expression Separator:

Capturing Parentheses:

Split() with Limit Argument

Share Follow edited Jun trăng tròn “20 at 9:12 Community♦ 1 1 1 silver badge answered Aug 26 “19 at 9:33 DeveloperDeveloper 572 5 5 silver badges 5 5 bronze badges địa chỉ cửa hàng a comment | 1

I remove the characters “” and do an split with “,”

let array = stringObject.replace(“”,””).split(“,”).map(String); tóm tắt Follow edited Dec 26 “17 at 11:37 KARTHIKEYAN.A 11.3k 4 4 gold badges 80 80 silver badges 91 91 bronze badges answered Jul 27 “17 at 3:51 Samuel IvanSamuel Ivan 2,190 18 18 silver badges 10 10 bronze badges showroom a phản hồi | 0

Split (“,”) can convert Strings with commas into a String array, here is my code snippet.

var input =”Hybrid App, Phone-Gap, Apache Cordova, HTML5, JavaScript, BootStrap, JQuery, CSS3, game android Wear API” var output đầu ra = input.split(“,”); console.log(output); share Follow answered Oct 16 “17 at 10:54 Hitesh SahuHitesh Sahu 30.5k 10 10 gold badges 145 145 silver badges 115 115 bronze badges add a phản hồi | 0var i = “”, j = i.replace(/(+?):/g, “”$1″:”).replace(/”/g,”””), k = JSON.parse(j); console.log(k)

// => declaring regular expression

=> match all a-z, A-Z, 0-9

(): => group all matched elements

$1 => replacement string refers to the first match group in the regex.

g => global flag

Share Follow edited Oct 26 “17 at 5:02 answered Aug 25 “17 at 9:03 KARTHIKEYAN.AKARTHIKEYAN.A 11.3k 4 4 gold badges 80 80 silver badges 91 91 bronze badges showroom a bình luận | 0

Example using Array.filter:

var str = “a,b,hi,ma,n,yu”; var strArr = Array.prototype.filter.call(str, eachChar => eachChar !== “,”); mô tả Follow edited Aug 1 “19 at 1:00 montrealist 5,201 10 10 gold badges 43 43 silver badges 57 57 bronze badges answered May 29 “19 at 9:28 AbhimanyuAbhimanyu 98 7 7 bronze badges showroom a phản hồi | 0Regexp

As more powerful alternative lớn split, you can use match

“0,1”.match(/d+/g)

let a = “0,1”.match(/d+/g) console.log(a); mô tả Follow answered Aug 25 “20 at 19:07 Kamil KiełczewskiKamil Kiełczewski 50.6k 18 18 gold badges 247 247 silver badges 222 222 bronze badges địa chỉ a comment | -1

Why don”t you vày replace , comma và split(“”) the string like this which will result into , furthermore, you could wrap the result into parseInt() to lớn transform element into integer type.

it(“convert string to lớn array”, function () ); chia sẻ Follow answered Feb 1 “17 at 10:28 Simple-SolutionSimple-Solution 3,865 11 11 gold badges 41 41 silver badges 63 63 bronze badges add a bình luận | Highly active question. Earn 10 reputation in order lớn answer this question. The reputation requirement helps protect this question from spam & non-answer activity.

Not the answer you’re looking for? Browse other questions tagged javascript arrays string deserialization or ask your own question.

The Overflow Blog Level Up: Creative coding with p5.js – part 3 Introducing The Key Featured on Meta Stack Overflow for Teams is now free for up lớn 50 users, forever Announcing “The Key™” – copy paste lượt thích you’ve never done before Linked 3Convert string containing arrays to actual arrays 2How to convert String Format data -1Convert array as string to lớn array javascript -4convert string lớn an array using JQuery 0what method can I use lớn separate strings inside array into individual arrays (using JavaScript)? -2JS: String “1, 2, 5” to lớn Array? 0javascript object: convert comma separated object (number) back into menu of arrays 0jquery output to array 769How can I convert a comma-separated string khổng lồ an array? 64Split a string by commas but ignore commas within double-quotes using Javascript See more linked questions Related 6854What is the difference between String và string in C#? 1352Convert JavaScript String khổng lồ be all lower case? 2798Convert bytes to a string 3159Sort array of objects by string property value 7802What does “use strict” vày in JavaScript, and what is the reasoning behind it? 7421How to kiểm tra whether a string contains a substring in JavaScript? 2999How to check if an object is an array? 3186How vì chưng I convert a String lớn an int in Java? 9248How can I remove a specific vật phẩm from an array? 1869Copy array by value Hot Network Questions Topology on the space of measurable functions Why does UV radiation from the Sun cause skin cancer? What options are there in Canada for treatment of severe depression và anxiety for pilots? Why doesn’t a microwave heat the air around food, in addition to the food itself? DEMOS commands: Cyrillic or Roman letters? Uppercase or lowercase? What is the meaning of “person specification” in a job advert? How vì we express someone does something unconsciously while he/she is asleep? Best way khổng lồ replicate this in latex Why a bank would propose a depositor to invest part of their money to mutual funds, instead of bank doing it itself? Is it possible to lớn generate light with an antenna? How to lớn perfectly overlap two photos? Book where humans & robots co-existed và slaves could earn freedom through playing games How vị I voice my opinion that the teaching of students is being neglected? Is mens semita tua the correct translation for mind your path? Was there a specific benefit to inverted (XOR) mouse cursors other than aesthetics? How come there aren’t many competing biologies on earth? Per the claim that Abraham kept the whole Torah, why didn’t he circumcise Ishmael và all his slaves earlier? do you get lớn keep a fraudulent money transfer that you are entitled to? Usage of cash in Europe during COVID Are new dividend investors severely disadvantaged by ongoing rising dividend growth stock prices? What was the 1 MHz bus used for on the đài truyền hình bbc micro series? In open-list voting systems, how bởi political parties ensure their leaders (and key figures) get elected? Trim elements from the ends of a menu Slide selected verticles along an edge more hot questions Question feed Subscribe khổng lồ RSS Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.