javascript comma separated list to array - javascript

I have this type of list from javascript:
Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina
I used the following code to convert to my output
var array = columnsload.split(",");
var string = JSON.stringify(columnsload);
var nameArray = string.split(',');
The output is like this :
"Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina"
But I really need it like this :
["Amila","Asanka","Imaad","Kelum","Lakshan","Sagara","Thilina"]
Anyone know how to get output like this?

the split function is enough to convert the string into an array;
var names = "Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina";
var nameArr = names.split(",");
console.log( nameArr );
http://www.w3schools.com/jsref/jsref_split.asp

Just do var nameArray = columnsload.split(',');. You dont need to stringify the array and then split it again, just one .split would be enough.
var columnsload = "Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina";
var nameArray = columnsload.split(',');
console.log(nameArray);
If you need the whole thing to be string, you can run a JSON.stringify on the array after.
var columnsload = "Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina";
var nameArray = columnsload.split(',');
console.log(JSON.stringify(nameArray));
// outputs ["Amila","Asanka","Imaad","Kelum","Lakshan","Sagara","Thilina"]
// as one string.

Related

String into multiple string in an array

I have not been coding for long and ran into my first issue I just can not seem to figure out.
I have a string "XX|Y1234$ZT|QW4567" I need to remove both $ and | and push it into an array like this ['XX', 'Y1234', 'ZT', 'QW4567'].
I have tried using .replace and .split in every way I could like of
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for(i = o; i <array.length; i++)
var loopedArray = array[i].split("|")
loopedArray.push(array2);
}
I have tried several other things but would take me awhile to put them all down.
You can pass Regex into .split(). https://regexr.com/ is a great tool for messing with Regex.
// Below line returns this array ["XX", "Y1234", "ZT", "QW4567"]
// Splits by $ and |
"XX|Y1234$ZT|QW4567".split(/\$|\|/g);
Your code snippet is close, but you've messed up your variables in the push statement.
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for (i = 0; i < array.length; i++) {
var loopedArray = array[i].split("|")
array2.push(loopedArray);
}
array2 = array2.flat();
console.log(array2);
However, this can be rewritten much cleaner using flatMap. Also note the use of let instead of var and single quotes ' instead of double quotes ".
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array
.split('$')
.flatMap(arrayI => arrayI.split('|'));
console.log(array2);
And lastly, split already supports multiple delimiters when using regex:
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array.split(/[$|]/);
console.log(array2);
You can do this as follows:
"XX|Y1234$ZT|QW4567".replace('$','|').split('|')
It will produce the output of:
["XX", "Y1234", "ZT", "QW4567"]
If you call the split with two parameters | and the $ you will get an strong array which is splittend by the given characters.
var array = "XX|Y1234$ZT|QW4567";
var splittedStrings = array.Split('|','$');
foreach(var singelString in splittedStrings){
Console.WriteLine(singleString);
}
the output is:
XX
Y1234
ZT
QW4567

How do I get JS to recognise an array insted of characters?

I am posting back a string from c# to JavaScript;
The string received looks like this:
arr = "[["A","B","C"],["D","E","F"]]";
I want to pass this to a function to create a table body in HTML but JavaScript always reads this as a string of chars NOT as an array - even when I use Array.from in example below:
CreatePositionsBodt(arr);
function CreatePositionsBodt(arr) {
alert(arr);
var asArr = Array.from(arr); function
}
change the surrounding quotes to apostrophe var arr = '[["A","B","C"],["D","E","F"]]';
and use eval() or JSON.parse()
var arr = '[["A","B","C"],["D","E","F"]]';
var myArray = eval(arr);
or
var arr = '[["A","B","C"],["D","E","F"]]';
var myArray = JSON.parse(arr);
note: if you have not done so in previous invisible lines of code, use var

Concatenate array into string

I have this:
var myarray = [];
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
And I want to get the string:
"first":"$firstelement","second": "$secondelement"
How can I do it?
What you have is invalid (even if it works), arrays don't have named keys, but numeric indexes.
You should be using an object instead, and if you want a string, you can stringify it as JSON
var myobject = {};
myobject["first"] = "$firstelement";
myobject["second"] = "$secondelement";
var str = JSON.stringify(myobject);
console.log(str)
First of all, you'd want to use an object instead of an array:
var myarray = {}; // not []
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
The easiest way, then, to achieve what you want is to use JSON:
var jsonString = JSON.stringify(myarray);
var arrayString = jsonString.slice(1, -1);
JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
var myarray = {};
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
console.log(JSON.stringify(myarray));
Use JSON.strinify()
JSON.stringify(item)

How to add string to array?

Example:
var imageBounds = [[40.712216, -74.22655], [46.773941, -79.12544]];
I need to create same from js. The problem that I am getting data in string format:
[40.712216, -74.22655], [46.773941, -79.12544]
so:
var mystr = "[40.712216, -74.22655], [46.773941, -79.12544]"
Ok, lets create empty array:
var myarr = []; // empty array
but how to add data to it? I know about push method but it's work only with arrays, and I have got text.
Make it valid JSON (by adding [ at beginning and ] at ending) afterward parse the string using JSON.parse method.
var mystr = "[40.712216, -74.22655], [46.773941, -79.12544]";
var res = JSON.parse('[' + mystr + ']');
console.log(res);

Javascript/Jquery Convert string to array

i have a string
var traingIds = "${triningIdArray}"; // ${triningIdArray} this value getting from server
alert(traingIds) // alerts [1,2]
var type = typeof(traingIds )
alert(type) // // alerts String
now i want to convert this to array so that i can iterate
i tried
var trainindIdArray = traingIds.split(',');
$.each(trainindIdArray, function(index, value) {
alert(index + ': ' + value); // alerts 0:[1 , and 1:2]
});
how to resolve this?
Since array literal notation is still valid JSON, you can use JSON.parse() to convert that string into an array, and from there, use it's values.
var test = "[1,2]";
parsedTest = JSON.parse(test); //an array [1,2]
//access like and array
console.log(parsedTest[0]); //1
console.log(parsedTest[1]); //2
Change
var trainindIdArray = traingIds.split(',');
to
var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');
That will basically remove [ and ] and then split the string
Assuming, as seems to be the case, ${triningIdArray} is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:
var traingIds = ${triningIdArray};
not
var traingIds = "${triningIdArray}";
check this out :)
var traingIds = "[1,2]"; // ${triningIdArray} this value getting from server
alert(traingIds); // alerts [1,2]
var type = typeof(traingIds);
alert(type); // // alerts String
//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds); // alerts 1,2
var trainindIdArray = traingIds.split(',');
​for(i = 0; i< trainindIdArray.length; i++){
alert(trainindIdArray[i]); //outputs individual numbers in array
}​

Categories

Resources