i would like to convert this string:
'[
['Row1 of first array', 'Row2 of first array'],
['Row1 of 2nd array', 'Row2 of 2nd array']
]'
Into an array with three arrays of one dimension and two items.
My expected output is an array with 2 elements:
Array 1
Array 2
And every array has two elements inside.
Is there any in Jquery to do this conversion?
That's not a valid string -- you're nesting single quotes inside of single quotes. However, if you convert the string into one using double quotes on the inside:
str = '[ ["Row1 of first array", "Row2 of first array"], ["Row1 of 2nd array", "Row2 of 2nd array"] ]'
then you could simply parse it as a JSON object:
arr = $.parseJSON(str); // returns a two-dimensional array
This is far, FAR safer than using eval, which should only be done when you know EXACTLY what's inside the string, and even then, it's a sign of a lazy developer. When using parseJSON, you know that you're getting either an object or an array when you're done -- when using eval, anything might happen.
I guess eval will work:
var str = eval("[['Row1 of first array', 'Row2 of first array'],['Row1 of 2nd array', 'Row2 of 2nd array']]");
console.log(str);
Related
I have arguments that will be passed by the user for a command. Each argument for a command will be seperated with a space, which will represent a new argument. Example: "arg1 arg2 arg3" converts to ["arg1", "arg2", "arg3"] where the output is a JS array. This can be done with a simple .split(" ").
However, my problem begin when trying to format an array as a command argument. My goal is to allow the user to enter an agument in the format of an array (e.g. Starts with [ may contain multiple elements seperated by a , and ends with a ]) so for example: "arg1 [elem1, elem2] arg3" converts to ["arg1", ["elem1", "elem2"], "arg3"] where the inner and outer array is a JS array.
I have tried using JSON.Parse() however, each element would require the user to have " at the start of each element which is too complex for the user and non essential to be inputting. Also, the elements may not always intend to be a string and may be Boolean, Number or a custom type.
As of currently, this has been my best solution but misses some requirements and also is non functional when an array has a space inside.
s.split(/[\[\]]|\s+/).filter(arg => arg.length > 1);
I have come up with some other solutions but all are missing one thing or another in the required specification set above. A solution that can handle nested arrays would be nice however it is non-essential and could make the solution alot more complex than it needs to be.
Let's assume no funny characters as the input. Also nesting not allowed.
var str = "arg1 [ elem1 , elem2,elem3 ] arg3";
console.log(str)
// removing white spaces from the [ array ]
str = str.replace(/\s*,\s*/g, ',');
str = str.replace(/\[\s*/g, '[');
str = str.replace(/\s*\]/g, ']');
// now split on words
var arr = str.split(/\s+/);
arr = arr.map(function(elem) {
// if begins with [ it is assumed to be an array to be splitted
return elem.charAt(0) == '[' ? elem.slice(1, -1).split(",") : elem;
})
console.log(arr)
I don't understand this behaviour:
var string = 'a,b,c,d,e:10.';
var array = string.split ('.');
I expect this:
console.log (array); // ['a,b,c,d,e:10']
console.log (array.length); // 1
but I get this:
console.log (array); // ['a,b,c,d,e:10', '']
console.log (array.length); // 2
Why two elements are returned instead of one? How does split work?
Is there another way to do this?
You could add a filter to exclude the empty string.
var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(function(el) {return el.length != 0});
A slightly easier version of #xdazz version for excluding empty strings (using ES6 arrow function):
var array = string.split('.').filter(x => x);
This is the correct and expected behavior. Given that you've included the separator in the string, the split function (simplified) takes the part to the left of the separator ("a,b,c,d,e:10") as the first element and the part to the rest of the separator (an empty string) as the second element.
If you're really curious about how split() works, you can check out pages 148 and 149 of the ECMA spec (ECMA 262) at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
Use String.split() method with Array.filter() method.
var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(item => item);
console.log(array); // [a,b,c,d,e:10]
console.log (array.length); // 1
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split
trim the trailing period first
'a,b,c,d,e:10.'.replace(/\.$/g,''); // gives "a,b,c,d,e:10"
then split the string
var array = 'a,b,c,d,e:10.'.replace(/\.$/g,'').split('.');
console.log (array.length); // 1
That's because the string ends with the . character - the second item of the array is empty.
If the string won't contain . at all, you will have the desired one item array.
The split() method works like this as far as I can explain in simple words:
Look for the given string to split by in the given string. If not found, return one item array with the whole string.
If found, iterate over the given string taking the characters between each two occurrences of the string to split by.
In case the given string starts with the string to split by, the first item of the result array will be empty.
In case the given string ends with the string to split by, the last item of the result array will be empty.
It's explained more technically here, it's pretty much the same for all browsers.
According to MDN web docs:
Note: When the string is empty, split() returns an array containing
one empty string, rather than an empty array. If the string and
separator are both empty strings, an empty array is returned.
const myString = '';
const splits = myString.split();
console.log(splits);
// ↪ [""]
Well, split does what it is made to do, it splits your string. Just that the second part of the split is empty.
Because your string is composed of 2 part :
1 : a,b,c,d,e:10
2 : empty
If you try without the dot at the end :
var string = 'a,b,c:10';
var array = string.split ('.');
output is :
["a,b,c:10"]
You have a string with one "." in it and when you use string.split('.') you receive array containing first element with the string content before "." character and the second element with the content of the string after the "." - which is in this case empty string.
So, this behavior is normal. What did you want to achieve by using this string.split?
try this
javascript gives two arrays by split function, then
var Val = "abc#gmail.com";
var mail = Val.split('#');
if(mail[0] && mail[1]) { alert('valid'); }
else { alert('Enter valid email id'); valid=0; }
if both array contains length greater than 0 then condition will true
Please be kind, I am a self learner. I try to find answers on my own sometimes.
```vaRiable =['2','4','6']
console.log("Result:"+vaRiable);
console.log("Result:",vaRiable);```
a particular array
vaRiable =['2','4','6']
when I console.log("Result :" +vaRiable); output = Result:2,4,6
console.log("Result :", vaRiable); output = Result: ['2','4','6']
what is the '+' doing to the string?
Why is there two types of output?
Can somebody quip me a one liner.It'll be great help. Thanks
"Result:"+vaRiable is a single expression. The Result: string is concatenated with the vaRiable, creating another string. When an array is coerced to a string, its elements are joined by commas. So you get 'Result:' + '2,4,6', or Result:2,4,6. That one string is then passed to console.log and printed to the console.
In contrast:
console.log("Result :", vaRiable);
sends two parameters to console.log. They don't get concatenated together, because they're separate parameters. When multiple parameters are passed to console.log, each is logged individually (though on the same line).
When you perform "Result:"+vaRiable the value of vaRiable is being type coerced into a string so that it can be concatenated to "Result". What you're doing in the first example is essentially creating a new string equal to "Result:2,4,6" because that's what arrays look like when they're cast to strings, similar to calling [2, 4, 6].toString() or [2, 4, 6].join(',').
In the second example, console.log() is doing regular console output of the array, which is why it keeps the brackets; it knows it's an array and to give it special formatting.
When you do ("Result:" + vaRiable), what the + is doing is to concatenate your string with your array into a single whole string.
When you do ("Result:", vaRiable) you're printing two messages. In this case you're not concatenating, the first message is a string Result: and the second message is an array ['2','4','6'].
to understand the split method I went over this link https://www.w3schools.com/jsref/jsref_split.asp
but not sure why comma not adding after 3 and why empty array not showing up in the output
is it just doing array concatenation
i debugged but not sure
can you guys let me know.
[123] + [] + 'foo'.split('');
"123f,o,o"
When the array is converted to string. Implicitly join() is called on it. So [].join() is '' that's why it doesn't show up in string.
But if you use some empty elements then it will show ,
console.log([123] + [,] + 'foo'.split(''));
How to concat arrays:
There can be different ways to concat two or more arrays. The modern one is using Spread Operator.
console.log([...[123], ...[],...'foo'.split('')]);
I have a json output where it gets two strings with format such as
[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]
[{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]
I want to parse these strings into one object. I have used the JSON.parse(data) but its giving me first string in object and not the all strings. How do I achieve this.
i want the output should be
[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"},
{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]
I guess you'd want an array with both of the objects inside, otherwise, please specify what is your expected output.
If you are unable to modify the JSON string received to make it look like a proper array, I'd substitute the '][' for a comma ',' so you can parse the JSON string and receive back an array with two objects inside, like so:
original = '[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}][{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]';
replaced = original.replace('][', ',');
parsed = JSON.parse(replaced);
Edited:
Just in case your input contains a line break between the closing and opening square brackets, your substitution should be like that:
replaced = original.replace(']\n[', ',');
2nd edit:
If your input contains more than two lines like these, there is no problem, your replace call will substitute every one of the matches if you write it like that:
replaced = original.replace(/\]\[/g, ',');
This is a regular expression that substitutes every occurence of ][ (expressed as \]\[ because these are special characters for regular expressions), with the help of the global flag specified at the end of the regular expression.
You can do:
var obj1 = [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]
var obj2 = [{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]
/* or */
var obj1 = JSON.parse('[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]')
var obj2 = JSON.parse('[{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]')
// then flatten into one array
var combined = [].concat.apply([], [obj1, obj2])
console.log(combined);
// [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}, {"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]