From well formatted string to an array - javascript

In JavaScript, what is the best way to convert a well formatted string ("4,5,7,2") to an array ([4,5,7,2]):
var _intStr="3,5,7,8" → var _intArr=[3,5,7,8]

var _intArr = _intStr.split(",");
One thing worth mentioning is that such value _intStr = "5,,1" will produce array with three items, two are the expected "5" and "1" and one item which is empty string.

Use the split function to split by a string or regex.
var arr = "1,2".split(",");
Now, if you actually want the elements of the resulting array to be numbers instead of strings, you can do something like this:
var arr = [];
"1,2,3,4,5".replace(/(?:'[^]*')|(?:[^, ]+)/g, function(match) {
if (match) {
arr[arr.length] = parseInt(match, 10);
}
});

Ok, thanks all for your helps.
I summarized your help in this way:
String.prototype.toArrInt = function(){
_intStr = this.replace(/^,+|,+(,)|,+$/g, '$1').split(',')
for(var i=0,_intArr=[];i<_intStr.length;_intArr.push(parseInt(_intStr[i++])));
return _intArr;
}
"3,5,6,,5".toArrInt();
Please correct me or improve my final code if is needed.
Thanks,
Antonio

Related

JS Array.splice return original Array and chain to it

I have a string with values like this a,b,c,d and want to remove a specific letter by index
So here is what I did str.split(',').splice(1,1).toString() and this is (obviously) not working since splice is returning the values removed not the original array
Is there any way to do the above in a one liner?
var str = "a,b,c,d";
console.log(str.split(',').splice(1,1).toString());
Thanks in advance.
You can use filter and add condition as index != 1.
var str = "a,b,c,d";
console.log(str.split(',').filter((x, i) => i != 1).toString());
Another strange solution. Destructure the array, remove the unwanted index, get an object and join the values of it.
var string = "a,b,c,d",
{ 1: _, ...temp } = string.split(',')
console.log(Object.values(temp).join(','));
The alternate way using regex replace
var str = "a,b,c,d";
console.log(str.replace(/,\w+/, ''))
Splice works in place, so oneliner is
const arr = "a,b,c,d".split(','); arr.splice(1,1); console.log(arr.toString());
If you want an string in a oneliner, you have to hardcode the index in a filter
console.log("a,b,c,d".split(',').filter((item, i) => i != 1).toString())
Or two slices (not performant at all)
const arr = "a,b,c,d".split(',')
console.log([...arr.slice(0,1),...arr.slice(2)].toString())

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

JavaScript convert string into literal comma list

Is there a way to convert "1,2" into 1,2 using native JS without some sort of wrapper?
"1,2".someMagic() \\ 1,2
Ultimately, I want to pass this as arguments to a function.
Firstly, no there is no way to convert "1,2" to literally 1,2. Because it is invalid type. 1,2 is better represented as an array
You can use .apply like below to send 1,2 as parameters (array format) to the function someMagic
someMagic.apply(context, [1,2]);
Apply would call someMagic and send 1,2 as parameters
function doSomething(param1, param2) {
return parseInt(param1)+parseInt(param2);
};
doSomething.apply(this, "1,2".split(","));
// returns 3
Perhaps this thread Converting an array to a function arguments list may be of interest to you.
Using split is the answer.
var string = "1,2";
var splitString = string.split(","); //use , as an parameter to split
http://www.w3schools.com/jsref/jsref_split.asp
Similar to user3146092's answer, this one will not rely on your function having to parseInt.
someMagic.apply(this, '1,2'.split(',').map(function(n) { return parseInt(n, 10); }));
You can create an array of numbers and pass them as your arguments, that in fact, is the best way to do it in JavaScript.
var nums = "1,2,3"
.split(",")
.map(function (num) { return parseInt(num, 10) });
Now you can pass nums as your arguments.
var str = "1,2,3,4,5,6";
var arr=[];
function process(str){
// split the string into tokens
arr = str.split(",");
// go through each array element
arr.forEach(function(val,index,ar){
// convert each element into integer
var temp = parseInt(val);
// repopulate array
arr[index] = temp;
});
}
process(str);
console.log(arr);

Nodejs: How to replace certain characters within an array with other characters in javascript

Say I have an array like this:
['test\\test1\\test2\\myfile.html', 'test\\test1\\test2\\myfile2.html']
I just want to replace all of the "\ \" characters with "/" and store this into a new array so that the new array should look like this:
['test/test1/test2/myfile.html', 'test/test1/test2/myfile2.html']
How could I go about doing this?
You can use map function of Array's to create a new Array
var replaced = ['test\\test1\\test2\\myfile.html', 'test\\test1\\test2\\myfile2.html'].map(function(v) {
return v.replace(/\\/g, '/');
});
console.log(replaced);
Since you mentioned node.js, you can just use .map:
var replaced = ['test\\test1\\test2\\myfile.html', 'test\\test1\\test2\\myfile2.html'].map(function (x) {
return x.replace(/\\/g, '/');
});
First of all you have to traverse the array using any iteration method.
This will help you with that:
For-each over an array in JavaScript?
I think you can use the replace function of the String object.
For more reference, please go to:
http://www.w3schools.com/jsref/jsref_replace.asp
Hope that helps
var test = ['test\\test1\\test2\\myfile.html', 'test\\test1\\test2\\myfile2.html'];
for(var i=0;i<test.length;i++) {
test[i] = test[i].replace(/\\/g,'/');
}
console.log(test);
outputs ["test/test1/test2/myfile.html", "test/test1/test2/myfile2.html"]

Elegant way to convert string of values into a Javascript array?

I have an ajax request that returns a list of values like this:
"1,2,3,4,5,6"
I need it to be a javascript array with numbers:
[1,2,3,4,5,6]
I tried:
var array = new Array("1,2,3,4,5,6".split(","))
But the numbers are still strings in the output:
["1","2","3","4","5","6"]
Is there a clean way to have it as a numbered array? Preferably without writing a function to iterate through it?
You need to loop through and convert them to numbers, like this:
var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = +array[i];
Or, the more traditional example:
var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = parseInt(array[i], 10);
A more jQuery-centric approach using jQuery.map():
var str = "1,2,3,4,5,6";
var arr = $.map(str.split(","), function(el) { return parseInt(el, 10); });
Not sure if this counts as writing a function but you can use the map function in jquery. I saw you listed as a tag so I assume you are using:
var stringArray = "1,2,3,4,5,6".split(",");
var numberArray = $.map(stringArray,
function(item, i)
{
return parseInt(item, 10);
});
// jquery must have a way to do what any modern browser can do:
var str= "1,2,3,4,5,6";
var arr= str.split(',').map(Number);
// returns an array of numbers
If you trust the ajax response, and if (for whatever reason) you're committed to not using a loop, you can always go with eval:
var str = "1,2,3,4,5,6";
var array = eval("[" + str + "]");
If you don't wish to expliclty iterate you can use array.map, javascripts map function.
array.map(callbackFunc, array);
var arr = array.map(function(x) {return parseInt(x);}, "1,2,3,4,5,6".split(","));
http://www.tutorialspoint.com/javascript/array_map.htm
Theres probably a better reference somewhere but I don't us javascript enough to have a good favorite reference site.
EDIT - i see jQuery has its own map, thats probably worth looking into.

Categories

Resources