Inserting array elements in parentheses - javascript

I got a sorted 2D array [[0,1],[1,1],[1,2],[2,3]] in javascript.
I have to convert this array into a string with each element separated by a pair of parentheses, eg. the above array should return a string as "(0,1)(1,1)(1,2)(2,3)"
i tried converting the array into string using join and tried inserting the parentheses at the begining and the end using traditional approach..
var elem = elements.join(')(').split();
elem.unshift('(');
elem.push(')');
console.log(elem.join());
but output i'm getting is a string as "(,0,0)(1,1)(1,1)(2,3,)"
how to remove the unwanted commas in between?

console.log([[0,1],[1,1],[1,2],[2,3]].map(a => `(${a})`).join(''));
//or
console.log([[0,1],[1,1],[1,2],[2,3]].reduce((result, item) => result + `(${item})`, ''));

Related

Why is the first match empty when using a split regex? [duplicate]

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

Comma separated string into multiple arrays separated by comma using javascript

How to convert comma separated string into multiple array strings separated by comma
var data = "34,2,76",
result = data.split(',').map(s => s.split(',')).slice(0);
console.log(result);
The result is [ ["34"], ["2"], ["76"] ].
How to get the output exactly as below as a string?
[ myarray.values[34], myarray.values[2], myarray.values[76] ]
Notice that I do not have double quotes and each array has a name. Also we do not know how many comma separated values will be passed.
I use react and some ES6 cool way will be even better.
You can split on the comma and then map each part using template literal interpolation and then join on the comma, prepending a opening square bracket and appending a closing square bracket to the result.
const data = "34,2,76";
const res = '[' + data.split(',').map(x => `myarray.values[${x}]`).join(',') + ']';
console.log(res);

Converting an array in curly braces to a square bracketed array

I've inherited a database that stores an array of strings in the following format:
{"First","Second","Third","Fourth"}
This is output as an ordered list in the application. We're replacing the front-end mobile app at the moment (ionic / angular) and want to do an ngFor over this array. In the first iteration, we did a quick and dirty replace on the curly brackets and then split the string on "," but would like to use a better method.
What is the best method for treating this type of string as an array?
You could do a string replacement of braces to brackets:
str.replace(/{(.*)}/, '[$1]')
This particular string could then be parsed as an array (via JSON.parse).
If you're looking to do the parsing to an array on the front end, would this work?:
const oldStyle = '{"First","Second","Third","Fourth"}'
const parseOldStyleToArray = input => input
.replace(/[\{\}]/g, '')
.split(',')
.map(item => item.replace(/\"/g, ''))
const result = parseOldStyleToArray(oldStyle)
console.dir(result)
Another way to do more widest replacement by key:value mapping.
str = '{"First","Second","Third","Fourth"}';
mapping = {
'{': '[',
'}': ']'
}
result = str.replace(/[{}]/g, m => mapping[m]);
console.log(result);

How to convert an array like string to array in node.js?

Actually I'm getting the arraylist from android device in node.js . But as it's in string form so I wanna convert it into an array . For that I've referred a lot of similar questions in SO but none of them were helpful . I also tried to use JSON.parse() but it was not helpful.
I'm getting societyList in form '[Art, Photography, Writing]'.Thus how to convert this format to an array?
Code:
var soc_arr=JSON.parse(data.societyList)
console.log(soc_arr.length)
use something like this
var array = arrayList.replace(/^\[|\]$/g, "").split(", ");
UPDATE:
After #drinchev suggestion regex used.
regex matches char starts with '[' and ends with ']'
This string is not valid JSON since it does not use the "" to indicate a string.
The best way would be to parse it yourself using a method like below:
let data = '[test1, test2, test3]';
let parts = data
.trim() // trim the initial data!
.substr(1,data.length-2) // remove the brackets from string
.split(',') // plit the string using the seperator ','
.map(e=>e.trim()) // trim the results to remove spaces at start and end
console.log(parts);
RegExp.match() maybe
console.log('[Art, Photography, Writing]'.match(/\w+/g))
So match() applies on any string and will split it into array elements.
Use replace and split. In addition, use trim() to remove the trailing and leading whitespaces from the array element.
var str = '[Art, Photography, Writing]';
var JSONData = str.replace('[','').replace(']','').split(',').map(x => x.trim());
console.log(JSONData);

.split() JS not "splitting" correctly?

I've got the following string:
str = "data1 data2 data3";
And I want to convert it to an array doing the following:
list = str.split(",");
But when I run this:
alert(list[1]);
…it does not retrieve "data2". And when I call this:
alert(data[0]);
¬it retrieves "data1, data2, data3".
Is there something wrong? I want to access the different words from the string by calling them from the number (0,1,2 - in this case) instead of all of them going to list[0]
The separator you are using in the split method is comma(,). But your input string does not have a comma, but it has spaces between words. So you need to split with space as the operator.
list = str.split(" ");
When separator is found, it is removed from the string and the substrings are returned in an array. If separator is not found, the array contains one element consisting of the entire string.
You are trying to split using "," as a separator. You will have to use:
list = str.split(" ");
It'll work that way ;)

Categories