How to make javascript turn a multidimensional array into a string? - javascript

I have a multidimensional array in javascript that I would like to be able to turn into a string while preserving brackets. I have taken a look at other questions such as javascript - Convert array to string while preserving brackets and the answers there didn't help me much.
My array could look like the following:
[[[0,0,1],1],[[1,0,0],4],[[1,0,1],5], [[0,1,1],3],[[1,1,0],6],[[0,1,0],2]]
When I print the array I see:
0,0,1,1,1,0,0,4,1,0,1,5,0,1,1,3,1,1,0,6,0,1,0,2
The output that I am expecting is what the original array looks like.
I have also tried the following code:
alert("[[" + myArray.join("],[") + "]]");
This works for almost everything, I get an output of:
[[0,0,1,1],[1,0,0,4],[1,0,1,5], ...
And I would like to see what the origional array looks like with the brackets. I would also like to stay away from JSON.stringify(); and JSON.parse();

JSON.stringify() and JSON.parse() will do exactly what you ask for. Try it out:
var arr = [[[0,0,1],1],[[1,0,0],4],[[1,0,1],5], [[0,1,1],3],[[1,1,0],6],[[0,1,0],2]];
var str = JSON.stringify(arr);
alert(str);
var parsed = JSON.parse(str);
alert(parsed);
console.log(parsed);

Related

Array to Newline String to Array again through HTML

I have an array that comes in from from my API that I would like to arrange in a way that is better for the user (namely, in a column as opposed to the typical comma separated printed array).
This is my JS Fiddle to give a clearer picture: https://jsfiddle.net/2z89owas/
My question is, how can I get output3 to display just like output (and maintain its status as an iterable array like it was as dates)?
First you should not be using value for an html element. You can use .value for extracting value from inputs. Change your line to:
var val = document.getElementById('output2').innerHTML;
Afterwards, you have to split the same way you did join.
var dates3 = val.split('<br>');
document.getElementById('output3').innerHTML = dates3;
You can directly use join, something like:
document.getElementById('output3').innerHTML = dates.join(',');
You can try mapping over the contents of dates instead, as so:
let datesElem = dates.map(date =>`<p>${date}</p>`);
// test: console.log(datesElem)
document.getElementById('output3').innerHTML = datesElem

Deserialize JSON string into array of list

I've a string
var my_str="[(0,10),(1,15),(2,48),(3,63),(4,25),(5,95),(6,41),(7,31),(8,5),(15,2)]";
I need to convert it into an array of list. For example,
alert(my_str[1])
would give an output of 1,15.
I've tried the following:
var myarray = JSON.parse(my_str);
but it throws the error "unexpected token ( in JSON at position 1"
I tried this
var myarray = JSON.parse(my_str);
but it throws error "unexpected token ( in JSON at position 1"
So I changed the structure of my string to:
var my_str="[[0,10],[1,15],[2,48],[3,63],[4,25],[5,95],[6,41],[7,31],[8,5],[15,2]]";
That worked like a charm ;)
The problem is that you are using a strange sintax for delimiting inner objects. It would be appropriate to use "[" and "]" instead of "(" and ")".
Anyway you can easily replace them with javascript and make your structure an array of arrays of strings. Sounds a bit creepy, but this way you can create a licit JSON object and benefit of JS native methods.
var my_array = JSON.parse(my_str.replace(/\(/g,'[').replace(/\)/g,']'))
you can now work on my_array object and retrieve couples of numbers using array indexes
my_array[1] ---> 1,15
You have to replace ( by '( and ) by )' ,, then , apply eval :
eval(arr.replace(/(/g,'\'(').replace(/)/g,')\''));
//> ["(0,10)", "(1,15)", "(2,48)", "(3,63)", "(4,25)", "(5,95)", "(6,41)", "(7,31)", "(8,5)", "(15,2)"]
This is a pretty naive idea, but does work (without JSON.parse or eval):
var arr = my_str.replace('[(', '').replace(')]', '').split('),(');
//> ["0,10", "1,15", "2,48", "3,63", "4,25", "5,95", "6,41", "7,31", "8,5", "15,2"]
var arr = my_str.split("),(")
arr[0] = arr[0].slice(2);
arr[arr.length-1] = arr[arr.length-1].slice(0,-2)

How to decode CSV to Array? Javascript

How to convert this CSV object to array or JSON .
Thanks
var obj = 3;ID;NAME;
You shouldn't really be rolling your own code to parse csv unless the format is very simple. You're going to end up with a massive amount of extra work to handle all the special cases that will arise.
You can use jQuery and jquery-csv:
Include the scripts:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//jquery-csv.googlecode.com/files/jquery.csv-0.71.min.js"></script>
Decode like this:
var csv = "heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2";
jsObject = $.csv.toObjects(csv)
Example in this plnkr: http://plnkr.co/edit/xS1IRNwNCwvLBKzpliBU?p=preview
If you want to split a comma delimited string into an array you can do it as such:
var csv = "a,string,seperated,by,comma"
var array = csv.split(",");
It needs to be a string, and then you can use the split function, as in:
var array= "3;ID;NAME".split(";");
See the MDN. Note you can split on any character, semicolon (as you have above), or if true CSV, a comma too.
my answer.
Thanks.
var obj = 3;ID;NAME;
var myArr = obj.split(';');
document.writeln(myArr[0]); //result "3"
document.writeln(myArr[1]); //result "ID"
document.writeln(myArr[2]); //result "NAME"

How to create an array with <input>?

I want to create an array with a html element. My main problem is, that i just get a string inside an array but no array.
Example: input is: 1,5,7,3,4
inside an array it look like this: ["1,5,7,3,4"] but i want it like this: [1,5,7,3,4]
I look for a solution made in javascript or better in jquery!
split will convert a string to an array.
var myArray = document.getElementById('myInput').value.split(',');
Use the split function to convert the string to an array.
For example:
<input type="text" id="myInput">1,5,7,3,4</input>
var myInput = $('#myInput').val();
var arr = myInput.split(','); // [1,5,7,3,4]

Javascript Object not working with Native javascript methods like match(), replace etc

Here is the issue:
I go this Code:
var str = {"Acc":10 , "adm_data":"Denied"};
When I do something like:
console.log(str.Acc.match(/[0-9]+/g)) // To Get the Integer Value from the "Acc" key
Firebug Screams:
TypeError: str.Acc.match is not a function
console.log(str.Acc.match(/[0-9]+/g));
See Image:
I always do something like:
var str = "Hello _10";
console.log(str.match(/[0-9]+/g)) // This Works
Why is the Object thingi not working?
PLEASE NOTE:
As mentioned by #Fabrício Matté. The issue was that I was trying to
pass an integer Value to the .match method which does not belong
to integers. The solution was to do what #kundan Karn Suggested. Something like:
str.Acc.toString().match(/[0-9]+/g)// Converting it first to string then match. It worked!
match function works with string. So convert it to string first
str.Acc.toString().match(/[0-9]+/g)
It works just fine: http://jsfiddle.net/nKHLy/
but in order to get rid of the error you might want to try:
var str = {"Acc":"Hello_10" , "adm_data":"Denied"};
console.log(String(str.Acc).match(/[0-9]+/g));
or
var str = {"Acc":"Hello_10" , "adm_data":"Denied"};
console.log(str.Acc.toString().match(/[0-9]+/g));
To know the difference between the 2 options, check: What's the difference between String(value) vs value.toString()

Categories