get data from javascript string - javascript

I have a string of the following structure:
positions = '15,-2,-3,15'
Which describes points, in this case A(15, -2), B(-3, 15).
Q How would you extract the data from a string like this?
It would be better to get the result as an array of somekind of struct (e.g., point[i].x, point[i].y), but a multidimensional array is also suitable (e.g. point[i][0], point[i][1]).

If you use split, it will turn the values into strings, so you would need to use parseInt() or parseFloat() to convert them back to numbers.
If you just want to get to the numbers quickly without converting them into an object, you can use the power of JSON.parse
var positions = '15,-2,-3,15';
var arrPositions = JSON.parse("[" + positions + "]");
A([arrPositions[0], arrPositions[1]);
B(arrPositions[2], arrPositions[3]);

Something like this would work, you split the string into tokens using the commas as deliminators, and then loop through that array creating some Point object with x and y.
var data = positions.split(',');
var points = [];
for(var i = 0; i < data.length - 1; i++) {
var x = data[i];
var y = data[++i];
points.push(new Point(x,y));
}

I would probably do:
positions = '15,-2,-3,15';
Arr = [];
pos = positions.split(',');
i = 0;
while( pos.length ){
Arr[i++] = pos.splice( 0, 2 );
}

Just for kicks:
(function f (e, s, p, r) {
r = e.exec(s);
return r ? [p(r[1], r[2])].concat(f(e, s, p)) : [];
}(/(-?\d+),(-?\d+)/g, '15,-2,-3,15',
function (x, y) { return { x: x, y: y }; }));

Related

How do I convert strings in an array to numbers using forEach?

I am trying to sum the contents of an array like these:
var cardsBen = [10,2]
var cardsAmy = [4,10]
When I use a for loop, it works.
for(var i = 0; i < cardsBen.length; i++){
cardsBen[i] = Number(cardsBen[i]);
}
When I use forEach, it doesn't convert.
cardsAmy.forEach(function(item)
{
Number(item);
});
I know this because, when I then reduce the arrays, I get 12 for Ben and 410 for Amy.
var sumBen = cardsBen.reduce(function(sum, nbr){return sum + nbr});
var sumAmy = cardsAmy.reduce(function(sum, nbr){return sum + nbr});
Primitive values can't be mutated. So when doing Number(item) you have to assign that back to the array like:
cardsAmy.forEach(function(item, i) {
cardsAmy[i] = Number(item);
});
And you can do that directly in reduce (without needing the above forEach code) like:
var sumBen = cardsBen.reduce(function(sum, nbr) { return sum + Number(nbr); }, 0);
// ^^^^^^^ ^
You could use reduce with an implicit casting to number with an unary plus +.
sum = array.reduce(function (s, v) {
return s + +v;
}, 0);

Javascript, adding multiple arrays to an array with a for loop

What is the best way to consolidate this code? As it is, it works perfectly, but it needs to go up to maybe 40-50 items long, so it needs to be shortened dramatically, (I assume, with a for loop).
I'm pretty much a novice when it comes to Javascript, and trying to add arrays to an array with a loop is confusing me immensely.
The "vac1.", "vac2." ...etc, variables are used later on in the code to add pointers onto a Google Maps map.
var x = count.count; // x = a value that changes (between 1 & 50)
if(x == 1){
locations = [
[vac1.vacancy_title, vac1.vacancy_latlng, vac1.vacancy_url, vac1.vacancy_location]
];
}
if(x == 2){
locations = [
[vac1.vacancy_title, vac1.vacancy_latlng, vac1.vacancy_url, vac1.vacancy_location],
[vac2.vacancy_title, vac2.vacancy_latlng, vac2.vacancy_url, vac2.vacancy_location]
];
}
if(x == 3){
locations = [
[vac1.vacancy_title, vac1.vacancy_latlng, vac1.vacancy_url, vac1.vacancy_location],
[vac2.vacancy_title, vac2.vacancy_latlng, vac2.vacancy_url, vac2.vacancy_location],
[vac3.vacancy_title, vac3.vacancy_latlng, vac3.vacancy_url, vac3.vacancy_location]
];
}
...etc etc...
I have tried using a for loop, but it doesn't work and I have no idea if I am anywhere close to figuring out how to do it correctly.
var x = count.count;
locations = [];
array = [];
for (i = 0; i < x; i++) {
array = [vac[i].vacancy_title, vac[i].vacancy_latlng, vac[i].vacancy_url, vac[i].vacancy_location];
locations.push(array);
}
Any help or advice would be greatly appreciated!
Thank you.
You need to consider them as a string:
var x = 5;
locations = [];
array = [];
for (i = 1; i <= x; i++) {
array = ['vac'+i+'.vacancy_title', 'vac'+i+'.vacancy_latlng', 'vac'+i+'.vacancy_url', 'vac'+i+'.vacancy_location'];
locations.push(array);
}
console.log(locations);
Create an array vac and use your previous code :
var x = count.count;
locations = [],
array = [],
vac = [ /* vac1, vac2, ...., vacn */ ];
for (i = 0; i < x; i++) {
array = [vac[i].vacancy_title, vac[i].vacancy_latlng, vac[i].vacancy_url, vac[i].vacancy_location];
locations.push(array);
}
You could use eval for the variable name and build an new array with another array for the wanted keys.
Basically you should reorganize yor program to use a solution without eval. An array could help. It is made for iteration.
var x = count.count,
i,
keys = ['vacancy_title', 'vacancy_latlng', 'vacancy_url', 'vacancy_location'],
locations = [];
object;
for (i = 1; i <= x; i++) {
object = eval('vac' + i);
locations.push(keys.map(function (k) { return object[k]; }));
}
Group the vac* elements in an array and then use slice to cut out as many as you want, then use map to generate the result array:
var vacs = [vac1, vac2 /*, ...*/]; // group the vacs into one single array
var x = count.count; // x is the number of vacs to generate
var locations = vacs.slice(0, x).map(function(vac) { // slice (cut out) x elements from the arrays vacs then map the cut-out array into your result array
return [vac.vacancy_title, vac.vacancy_latlng, vac.vacancy_url, vac.vacancy_location];
});
Because any global variable is a property of the global object :
var vac1 = "whatever";
console.lof(window.vac1); // => logs "whatever"
console.lof(window["vac1"]); // => accessed as an array, logs "whatever" too
You could use the global object and access it as an array to look for your vac1, vac2, vac3 variables :
var x = count.count, i;
locations = [],
array = [],
var globalObject = window; // or whatever the global object is for you
var vac; // this will be used to store your vac1, vac2, etc.
for (i = 0; i < x; i++) {
vac = globalObject["vac"+i]; // the "vac" + i variable read from the global object
if (vac !== undefined) {
array = [vac.vacancy_title, vac.vacancy_latlng, vac.vacancy_url, vac.vacancy_location];
locations.push(array);
}
}

Javascript: Convert 2D Integer array to base64 string and back

I'm not much familiar with javascript, but I faced a need to send and receive big static 2D integer arrays (where values are > 255) as base64 strings (this is essential). At the moment I've came up with this straightforward and inefficient solution converting them element-wise and manually constructing strings, which, as far as I understand, should involve a lot of copying of the data and turns to be very slow.
Can it be done in a more efficient way, if possible without usage of some big side libraries like Node.js, etc?
//----------- serializing/deserializing procedures
//encoding int contours array to be sent as base64 string
function getBase64IntArray(arr) {
var width = arr.length;
//This works given the inner arrays length never changes.
var height = arr[0].length;
//string that would contain data
var str = width.toString()+","+height.toString()+",";
for(var x = 0; x < height; x++) {
for(var y = 0; y < width; y++) {
str = str + arr[x][y].toString() + ",";
}
}
var str64 = btoa(str);
return str64;
}//getBase64IntArray
//deconding this string back to array
function getIntArrayfromBase64(str64) {
var str = atob(str64);
//first occurence of ","
var width_str = str.substr(0,str.indexOf(','));
str = str.substr(str.indexOf(',')+1); // cut the beginning
//again first occurence of ","
var height_str = str.substr(0,str.indexOf(','));
str = str.substr(str.indexOf(',')+1); // cut the beginning
var width = parseInt(width_str);
var height = parseInt(height_str);
//declare new array and fill it
var arr = new Array(height);
var curr_str = "";
for(var x = 0; x < height; x++) {
arr[x] = new Array(width);
for(var y = 0; y < width; y++) {
//first occurence of ","
curr_str = str.substr(0,str.indexOf(','));
// cut the beginning
str = str.substr(str.indexOf(',')+1);
arr[x][y]=parseInt(curr_str);
}
}
return arr;
}// getIntArrayfromBase64
Sending/receiving works:
//----------- example usage
function send(){
//encoding to base64
var arr = [
[1, 2],
[3, 4]
];
var base64 = getBase64IntArray(arr);
webSocket.send(base64);
}
webSocket.onmessage = function(event){
//reading array as base64 string
var arr = getIntArrayfromBase64(event.data);
var width = arr.length;
var height = arr[0].length;
writeResponse("Received "+width+" "+height+" "+arr[0][0]+arr[1][1]);
};
How about going through JSON? JSON will add minimal overhead to the wire format, but the serialization/deserialization will be fast, because it's implemented natively.
function getBase64IntArray(arr) {
return btoa(JSON.stringify(arr))
}
function getIntArrayfromBase64(str64) {
return JSON.parse(atob(str64))
}

How do I square a number's digits?

How do I square a number's digits? e.g.:
square(21){};
should result in 41 instead of 441
This is easily done with simple math. No need for the overhead of string processing.
var result = [];
var n = 21;
while (n > 0) {
result.push(n%10 * n%10);
n = Math.floor(n/10);
}
document.body.textContent = result.reverse().join("");
In a loop, while your number is greater than 0, it...
gets the remainder of dividing the number by 10 using the % operator
squares it and adds it to an array.
reduces the original number by dividing it by 10, dropping truncating to the right of the decimal, and reassigning it.
Then at the end it reverses and joins the array into the result string (which you can convert to a number if you wish)
I think he means something like the following:
var output = "";
for(int i = 0; i<num.length; i++)
{
output.concat(Math.pow(num[i],2).toString());
}
I believe this is what the OP is looking for? The square of each digit?
var number = 12354987,
var temp = 0;
for (var i = 0, len = sNumber.length; i < len; i += 1) {
temp = String(number).charAt(i);
output.push(Number(temp) * Number(temp));
}
console.log(output);
Split the string into an array, return a map of the square of the element, and rejoin the resulting array back into a string.
function squareEachDigit(str) {
return str.split('').map(function (el) {
return (+el * +el);
}).join('');
}
squareEachDigit('99') // 8181
squareEachDigit('52') // 254
DEMO
function sq(n){
var nos = (n + '').split('');
var res="";
for(i in nos){
res+= parseInt(nos[i]) * parseInt(nos[i]);
}
return parseInt(res);
}
var result = sq(21);
alert(result)
You'll want to split the numbers into their place values, then square them, then concatenate them back together. Here's how I would do it:
function fn(num){
var strArr = num.toString().split('');
var result = '';
for(var i = 0; i < strArr.length; i++){
result += Math.pow(strArr[i], 2) + '';
}
return +result;
}
Use Math.pow to square numbers like this:
Math.pow(11,2); // returns 121

Applying math to values in an array

I have an array:
var myarray = ["5,35.0", "15,45.0", "25,45.0", "35,50.0", "45,60.0", "55,65.0", "65,60.0", "75,60.0", "85,70.0", "95,80.0"]
the values correspond to x,y points on a graph.
I need to apply math to each y value to change the y-axis scale. To keep it simple, let's say I need to multiply each y value by 2.
How would I go about this?
Use map to loop over the array, converting the string to a pair of numbers, performing the addition ensuring that the decimal place is kept intact.
var out = myarray.map(function (el) {
var xy = el.split(',').map(Number);
xy[1] = (xy[1] * 2).toFixed(1);
return xy.join(',');
});
Fiddle
You need to loop through every element and split them via ',' and then do the MATH over it and save it back.
Say,
for(var i=0;i<myarray.length;i++){
var temp = (parseFloat(myarray[i].split(',')[1])).toFixed(2);
temp = temp * 2;
myarray[i] = myarray[i].split(',')[0] + "," + temp;
}
Roughly,
var myarray = ["5,35.0", "15,45.0", "25,45.0", "35,50.0", "45,60.0", "55,65.0", "65,60.0", "75,60.0", "85,70.0", "95,80.0"];
var y = 0;
var x = 0;
for(var i in myarray) {
y = parseFloat(myarray[i].split(",")[1]);
x = parseFloat(myarray[i].split(",")[0]);
y = y * 2; // or your operation
myarray[i] = x + "," + y;
}
console.log(myarray);
HTH

Categories