How to calculate two values from bracket in javascript - javascript

I am creating geofencing featured website. So I need to calculate some expression. I have two values related to latitude and longitude.
for e.g: var value = '(41.878113,-87.629798)'
How to separate above two values in javascript

The Google Maps LatLng API provides .lat() and .lng() functions for accessing them individually. You can use them like this:
var coords = new google.maps.LatLng(42.878113,-87.629798);
console.log(coords.lat()); // 42.878113
console.log(coords.lng()); // -87.629798

That's not valid JavaScript. (Post was edited, it wasn't valid at first)
One method you could do is define it as an array:
var cords = [41.878113, -87.629798];
From here you could reference it like so:
cords[0]; // Out: 41.878113
cords[1]; // Out: -87.629798

An easy way would be to separate the string at the , then remove non-numeric characters
var value = '(41.878113,-87.629798)';
var parts = value.split(',');
//=> ["(41.878113", "-87.629798)"]
var lat = parts[0].replace(/[^\d.-]/g, '');
//=> "41.878113"
var lng = parts[1].replace(/[^\d.-]/g, '');
//=> "-87.629798"
Now you can use them in some sort of calculation
calculateSomething(lat, lng);
Which would be the same as
calculateSomething("41.878113", "-87.629798");

If value is a String that is always in that format and you want an Array that contains the 2 values in String format , this example should suffice
var value = '(41.878113,-87.629798)';
document.getElementById('out').textContent = JSON.stringify(value.slice(1, -1).split(','), null, 2);
<pre id="out"></pre>

Related

how to change thousands line of number to an array in JavaScript

I got thousands lines of number
142156
108763
77236
78186
110145
126414
115436
133275
132634
......
82606
and I wanna change it to an array [142156, 108763, 108763, 77236, 78186, ....]
If I could make all these number assigned to a variable, I could choose either to use the RegExp or to convert to string first and then array.
any idea how to make it as a variable or other better suggestions?
Read as string from file then split the string at line breaks and map the resultant array of strings to number
const str = `142156
108763
77236
78186
110145
126414
115436
133275
132634`;
const arr = str.split(/\r?\n/).map(Number)
console.log(arr)
You can use following method.
const nums = document.getElementById("numbersDiv").innerHTML;
const numsToArr = nums.split('\n').map(Number)
console.log({ numsToArr } )
<div id="numbersDiv">142156
108763
77236
78186
110145
126414
115436
133275
132634</div>

how to convert json array result object as non array values

I have a json result of latitude longiude as an array result like this, [13.0801721, 80.2838331] .
I want to convert this just as comma seprated valueswithout array brackets lik this, 13.0801721, 80.2838331. Please help
Here is my problem.
i want to get this array of
var myLatlng = new google.maps.LatLng([13.0801721, 80.2838331]); json result like this
var myLatlng = new google.maps.LatLng(13.0801721, 80.2838331);
please see screenshot
enter image description here
You can call your function like this:
let result=[13.0801721, 80.2838331];
let myLatlng = new google.maps.LatLng(...result);
This uses the Spread Syntax

JSON to JS array

JSON:
[{"CDATE":"0000-00-00","DISTANCE":"0"},
{"CDATE":"0000-00-00","DISTANCE":"1"},
{"CDATE":"0000-00-00","DISTANCE":"2"},
{"CDATE":"0000-00-00","DISTANCE":"3"}]
Is it possible to put all the distance value in their own array in JS? The formatting will be consistent as it comes from an API and is always formatted correctly.
What I've tried:
var arry = [ /* JSON noted above */ ];
alert(arry[1])
and
var arry = JSON.parse([ /* JSON noted above */ ]);
alert(arry[1])
Expected:
1
Actual:
{"CDATE":"0000-00-00","DISTANCE":"1"}
and the other gives an error.
I would like to extract just the DISTANCE value as an array of DISTANCE
I've tried JSON.parse() but I don't think this is what I am after as it hasn't worked for me.
Use .map
var data = [{"CDATE":"0000-00-00","DISTANCE":"0"},
{"CDATE":"0000-00-00","DISTANCE":"1"},
{"CDATE":"0000-00-00","DISTANCE":"2"},
{"CDATE":"0000-00-00","DISTANCE":"3"}];
var distance = data.map(el => el.DISTANCE);
console.log(distance[2]);
console.log(distance);
It is already a valid json so you do not need to use JSON.parse()

how can i convert my data in javascript server side to json object and array?

i'm working with xpages and javascript server side i want to convert the fields in format json then i parse this dat and i put them in a grid,the problem is that these fields can contains values :one item or a list how can i convert them in json ?
this is my code :
this.getWFLog = function ()
{
var wfLoglines = [];
var line = "";
if (this.doc.hasItem (WF.LogActivityPS) == false) then
return ("");
var WFLogActivityPS = this.doc.getItem ("WF.LogActivityPS");
var WFActivityInPS = this.doc.getItem ("WFActivityInPS");
var WFActivityOutPS = this.doc.getItem ("WFActivityOutPS");
var WFLogDecisionPS = this.doc.getItem ("WF.LogDecisionPS");
var WFLogSubmitterPS = this.doc.getItem ("WF.LogSubmitterPS");
var WFLogCommentPS = this.doc.getItem ("WF.LogCommentPS");
var WFLogActivityDescPS = this.doc.getItem ("WF.LogActivityDescPS");
var Durr =((WFActivityOutPS-WFActivityInPS)/3600);
var json= {
"unid":"aa",
"Act":WFLogActivityPS,
"Fin":WFActivityOutPS,
"Durr":Durr,
"Decision":WFLogDecisionPS,
"Interv":WFLogSubmitterPS,
"Instruction":WFLogActivityDescPS,
"Comment":WFLogCommentPS
}
/*
*
* var wfdoc = new PSWorkflowDoc (document1, this);
histopry = wfdoc.getWFLog();
var getContact = JSON.parse(histopry );
*/ }
Careful. Your code is bleeding memory. Each Notes object you create (like the items) needs to be recycled after use calling .recycle().
There are a few ways you can go about it. The most radical would be to deploy the OpenNTF Domino API (ODA) which provides a handy document.toJson() function.
Less radical: create a helper bean and put code inside there. I would call a method with the document and an array of field names as parameter. This will allow you to loop through it.
Use the Json helper methods found in com.ibm.commons.util.io.json they will make sure all escaping is done properly. You need to decide if you really want arrays and objects mixed - especially if the same field can be one or the other in different documents. If you want them flat use item.getText(); otherwise use item.getValues() There's a good article by Jesse explaining more on JSON in XPages. Go check it out. Hope that helps.
If an input field contains several values that you want to transform into an array, use the split method :
var WFLogActivityPS = this.doc.getItem("WF.LogActivityPS").split(",")
// input : A,B,C --> result :["A","B","C"]

convert or parse string to JSON object

There was an interview question(Javascript) which my friend and me unable to solve it for a long time, so thought of asking here,
Question:
String:
2014<18.3,11.4,12.1,19.5,1000&&11.2,34.5,67.1,18,20000>name=sample,position=engineer,company=abc
and the end reult should be a JSON Objwct with following format. Can anyone please help to solve this issue.
Output:
{[
{"Proposal":"2014"},
{"values":"[18.3,11.4,12.1,19.5],[11.2,34.5,67.1,18]"},
{"Items":"[1000,20000]"},
{"name":"sample"},
{"position":"engineer"},
{"company":"abc"},
]}
Expecting a solution and explanation please.
Thanks,
Basky
Here is your solution.
Input string should have all the parameter, if any of the parameter is missing below code will break.
Logic is dynamic to support any number of numeric values where as last digit will consider as Items.
Logic also support the n number of key/value pair in the input string.
Check below code in console.
var JsonOutput = [];
var sRawInput = "2014<18.3,11.4,12.1,19.5,1000&&11.2,34.5,67.1,18,20000>name=sample,position=engineer,company=abc";
JsonOutput.push({ "Proposal" : sRawInput.split("<")[0] });
var oValues = sRawInput.split("<")[1].split(">")[0].split("&&");
var oActualValues = [];
var oActualItems = [];
$(oValues).each(function(Ind, Val){
oActualValues.push(Val.split(",").slice(0, Val.split(",").length - 1).join());
oActualItems.push(Val.split(",")[Val.split(",").length - 1]);
});
JsonOutput.push({ "Values" : oActualValues });
JsonOutput.push({ "Items" : oActualItems });
var OtherValues = sRawInput.split(">")[1].split(",");
$(OtherValues).each(function(Ind, Val){
JsonOutput.push(JSON.parse("{\"" + Val.split("=")[0] + "\":\"" + Val.split("=")[1] + "\"}"));
});
console.log(JsonOutput);
console.log(JSON.stringify(JsonOutput));
Note:
Values is incorrect as it should contain 2 arrays and not a single array.
Items is incorrect as it should contain numbers and not a string.
Also the outside wrapper should be an obj {}

Categories

Resources