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);
Related
How can I convert a string containing floats written out (not stored as JSON or something like that) into a Float32Array? I tried this but it doesn't work:
var str = "2.3 4.3 3.145";
var arr1 = parseFloat(str);
var arr2 = new Float32Array(arr1);
You have to split the values up, and then you can use Float32Array.from with the mapping callback:
const arr = Float32Array.from(str.split(" "), parseFloat);
const str = "2.3 4.3 3.145";
const arr = Float32Array.from(str.split(" "), parseFloat);
console.log(arr);
Note: Unlike parseInt, it's safe to use parseFloat the way it's used above, it ignores all but its first argument so it doesn't care that it gets called with more than one argument by from. If you had to do something like this to create (say) a Uint8Array, you couldn't use parseInt as above because it would be confused by the second argument it would receive. In that case, an arrow function is a simple way to fix it (and lets you be specific about the number base as well):
const arr = Uint8Array.from(str.split(" "), n => parseInt(n, 10));
You can split, then map to an array of floats
const str = "2.3 4.3 3.145";
const arr1 = str.split(' ').map(parseFloat);
const arr2 = new Float32Array(arr1);
console.log(arr1);
console.log(arr2);
Initial :
var a = [["1","John"] , ["2","Alex"]]
Expected :
var a = [[1,"John"] , [2,"Alex"]]
Appreciate advise on how to convert the array.
Array.prototype.map() and coercing the first index to integer of nested array could be converted to your expected one.
var a = [["1","John"],["2","Alex"]]
.map(item => [+item[0], item[1]])
console.log(a);
Note: Here + is coercing the string to integer.
You can use the forEach method and use parseInt to turn the index you want into an integer. Dont forget your comma to separate the index of the outter array
var a = [["1","John"], ["3","Alex"]];
a.forEach((innerArray)=> innerArray[0] = +innerArray[0]);
console.log(a)
Alternatively, you can use Array.map(), together with the Number() function, to carry out the type conversion.
const a = [['1', 'John'], ['2','Alex']];
const result = a.map(item => [Number(item[0]), item[1]]);
console.log(result);
Use parseInt() for each string that needs to be converted to integer.
I have an array of string like:
var myArray=['rwt-cable1','rwt-cable42','rwt-cable40',...]
But what I am really interested in is:
['cable1','cable42','cable40',...]
What would be the best way? I'm currently looping through items and extract substrings to get my output array.
You could use split and map function
var res = ['rwt-cable1', 'rwt-cable42', 'rwt-cable40'].map(e => e.split('-')[1]);
console.log(res);
You can do it by using a regular expression:
var myArray= ['rwt-cable1','rwt-cable42','rwt-cable40'];
myArray = myArray.map(v => v.replace(/^rwt\-/,""));
console.log(myArray); //["cable1", "cable42", "cable40"]
The regex ^rwt\- will match the text rxt- at the beginning of the string.
The alternative using Array.map and Array.slice functions:
var myArray = ['rwt-cable1','rwt-cable42','rwt-cable40'],
result = myArray.map(function(v){ return v.slice(4); });
console.log(result); // ["cable1", "cable42", "cable40"]
A simpler approach would be
['rwt-cable1', 'rwt-cable42', 'rwt-cable40'].map(x => x.replace('rwt-', ''))
// ["cable1", "cable42", "cable40"]
Lets say I have a URL such as /test-resource/test1-100/test2-200/test3-300
I want to split the url and store 100, 200 and 300 in a array, object or string.
Here we go
var str = '/test-resource/test1-100/test2-200/test3-300';
var re = /(test\d+)\-(\d+)/g;
var arr = [];
while( res = re.exec(str) ) {
arr[res[1]] = res[2];
alert('match:' + res[0] + ' property:' + res[1] + ' value:' + res[2]);
}
console.log(arr);
Try this, but most likely you will have to change the logic accordingly to the url params you have.
var x = "/test-resource/test1-100/test2-200/test3-300";
var y = x.split("/");
var one_hundred = y[2].split('-')[1];
var two_hundred = y[3].split('-')[1];
var three_hundred = y[4].split('-')[1];
Source:
split
Here's a functional approach using lodash:
_(url)
.split('/')
.map(_.bindKey(/\d+$/, 'exec'))
.map(_.first)
.compact()
.map(_.ary(parseInt, 1))
.value()
// → [ 100, 200, 300 ]
Here's how it works:
split() breaks the URL down into it's parts, so now you have an array.
map() uses bindKey() to create a callback function that executes a regular expression against each URL part. So now you have an array of regular expression results.
map() uses first() to grab only the first item from the regular expression results. Now you have an array of number strings, or undefined.
compact() removes the undefined items.
map() uses parseInt() to transform the array of strings into an array of numbers. ary() makes sure only one argument is passed to parseInt().
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