take from a string specific values - javascript

Hello I want to take fro a string i javascript specific values , the string has this format
[
{
"st_asgeojson": "{\"type\":\"MultiLineString\",\"coordinates\":[[[23.4582348,37.5062675],[23.4577141,37.5066109],[23.4572601,37.5070038],[23.4566746,37.507301],[23.455698,37.5076256],[23.4549737,37.5079214],[23.4545445,37.5080235],[23.4538579,37.5078873],[23.4325504,37.5231202],[23.4324646,37.5234265],[23.4324646,37.5236308],[23.4326363,37.5237669]]]}"
},
{
"st_asgeojson": "{\"type\":\"MultiLineString\",\"coordinates\":[[[23.4568043,37.5042114],[23.4566078,37.5040436],[23.4567394,37.5038528],[23.4571075,37.5037422],[23.4575424,37.5035515],[23.4580841,37.5031548],[23.4589958,37.5027237]]]}"
}
]
from this string i want to make an new 2d array , in this array i want to put only the coordinates.
for example i want to have in first row the first st_asgeojson coordinates [23.4582348,37.5062675],....,[23.4326363,37.5237669] and the second row the other st_asgeojson coordinates [23.4568043,37.5042114],[23.4566078,37.5040436],......,[23.4589958,37.5027237].
Is this posible to do it ?
i try to str.split("[ ]") but is show me the same as the string i have first.

The original string is JSON, so you first have to convert it to an array with JSON.parse():
var arr = JSON.parse(str);
Then the value of the st_asgeojson property is another JSON-encoded object, so you'll have to parse that as well:
var first_coords = JSON.parse(arr[0].st_asgeojson).coordinates[0][0];
var second_coords = JSON.parse(arr[1].st_asgeojson).coordinates[0][0];
There's no [ ] anywhere in the string, so I'm not sure what you expected str.split('[ ]') to achieve. Did you mean to use a regexp, str.split(/ /) to split it on the spaces?
To get them all with a loop do:
var arrLeng = arr.length;
for (var i = 0; i < arrLeng; i++) {
var coordArray = JSON.parse(arr[i].st_asgeojson).coordinates;
var coordArrLeng = coordArray.length;
for (var j = 0; j < coordArrLeng; j++) {
var coords = coordArray[0][0];
var coordLeng = coords.length;
for (var k = 0; k < coordLeng; k++) {
alert(coords[k]);
}
}
}

Related

Checking to see if key-value has the same value

So I'm turning a .csv file into an array of key-value pairs, I'm trying to print each unique value and i'm trying to figure out how I can check to make sure the values aren't identical. So for example:
var data = $.csv.toObjects(csv);
will turn everything into
[
{heading1:"value1_1",heading2:"value2_1",heading3:"value3_1",heading4:"value4_1",heading5:"value5_1"}
{heading1:"value1_2",heading2:"value2_2",heading3:"value3_2",heading4:"value4_2",heading5:"value5_2" }
]
I want to check if heading1 has the same value in both instances and if it does to only print the first instance of that value.
Convert your data into key–value pairs, where keys are the values from "heading1" like so:
var data = [
{heading1:"value1_1",heading2:"value2_1",heading3:"value3_1",heading4:"value4_1",heading5:"value5_1"},
{heading1:"value1_2",heading2:"value2_2",heading3:"value3_2",heading4:"value4_2",heading5:"value5_2" },
];
var filtered = {};
for (var i = 0, max = data.length; i < max; i++) {
var record = data[i];
if (!filtered[record.heading1]) {
filtered[record.heading1] = {};
}
filtered[record.heading1] = record;
}
var keys = Object.keys(filtered);
for (var i = 0, max = keys.length; i < max; i++) {
console.log(filtered[keys[i]]); // do print
}

How to generate an array with repeated string javascript

How to generate an array with function like this?
var name = ["monkey","monkey"..."horse","horse",..."dog","dog",..."cat","cat"...]​
In my real case, I may have to repeat each name 100 times..
Assuming that you already have that words in a array try this code:
var words = ["monkey", "hourse", "dog", "cat"];
var repeatWords = [];
for(var i = 0; i < words.length; i++)
{
for(var j = 0; j < 100; j++)
{
repeatWords.push(words[i]);
}
}
You can try this, specifying the words to be used, and the times to create the array you need.
var neededWords = ["Cat", "Hourse", "Dog"];
var finalArray = [];
var times = 10;
for (var i = 0; i < neededWords.length; i++) {
for (var n = 0; n < times; n++) {
finalArray.push(neededWords[i]);
}
}
console.log(finalArray);
Hope that helps!
If I understood correctly you need a function that takes as an argument a collection of items and returns a collection of those items repeated. From your problem statement, I assumed that the repetition has to be adjusted by you per collection item - correct me if I am wrong.
The function I wrote does just that; it takes an object literal {name1:frequency1,name2:frequency2..} which then iterates over the keys and pushes each one as many times as indicated by the associated frequency in the frequencyMap object.
function getRepeatedNames( frequencyMap ) {
var namesCollection = [];
Object.keys(frequencyMap).forEach(function(name,i,names){
var freq = frequencyMap[name];
freq = (isFinite(freq)) ? Math.abs(Math.floor(freq)) : 1;
for (var nameCounter=0; nameCounter<freq; nameCounter++) {
namesCollection.push(name);
}
});
return namesCollection;
}
Non-numeric values in the frequency map are ignored and replaced with 1.
Usage example: If we want to create an array with 5 cats and 3 dogs we need to invoke
getRepeatedNames({cat: 2, dog: 3}); // ["cat","cat","dog","dog","dog"]

Javascript arrays storing values

There might be a very simple solution my problem but just not being able to find one so please help me to get to my solution in the simplest way...
The issue here is that I have data being displayed in a tabular form. Each row has 5 columns and in one of the columns it shows multiple values and so that's why I need to refer to a value by something like this row[1]['value1'], row[1]['value2'] & then row[2]['value1'], row[2]['value2'].
I declare the array
var parray = [[],[]];
I want to store the values in a loop something like this
for(counter = 0; counter < 10; counter ++){
parray[counter]['id'] += 1;
parray[counter]['isavailable'] += 0;
}
Later I want to loop through this and get the results:
for (var idx = 0; idx < parray.length; idx++) {
var pt = {};
pt.id = parray[schctr][idx].id;
pt.isavailable = parray[schctr][idx].isavailable;
}
Obviously iit's not working because Counter is a numeric key and 'id' is a string key ..my question how do I achieve this ??
Thanks for all the answers in advance.
JS has no concept of "associative arrays". You have arrays and objects (map). Arrays are objects though, and you can put keys, but it's not advisable.
You can start off with a blank array
var parray = [];
And "push" objects into it
for(counter = 0; counter < 10; counter++){
parray.push({
id : 1,
isAvailable : 0
});
}
Then you can read from them
for (var idx = 0; idx < parray.length; idx++) {
// Store the current item in a variable
var pt = parray[idx];
console.log(pt);
// read just the id
console.log(parray[idx].id);
}
Like I did here
What you want inside your array is just a plain object:
// just a regular array
var parray = [];
for(var counter = 0; counter < 10; counter++){
// create an object to store the values
var obj = {};
obj.id = counter;
obj.isavailable = 0;
// add the object to the array
parray.push(obj);
}
later:
for (var idx = 0; idx < parray.length; idx++) {
var pt = parray[idx];
// do something with pt
}

splitting a string based on delimiter using javascript

Hi I'm trying to split a string based on multiple delimiters.Below is the code
var data="- This, a sample string.";
var delimiters=[" ",".","-",","];
var myArray = new Array();
for(var i=0;i<delimiters.length;i++)
{
if(myArray == ''){
myArray = data.split(delimiters[i])
}
else
{
for(var j=0;j<myArray.length;j++){
var tempArray = myArray[j].split(delimiters[i]);
if(tempArray.length != 1){
myArray.splice(j,1);
var myArray = myArray.concat(tempArray);
}
}
}
}
console.log("info","String split using delimiters is - "+ myArray);
Below is the output that i get
a,sample,string,,,,This,
The output that i should get is
This
a
sample
string
I'm stuck here dont know where i am going wrong.Any help will be much appreciated.
You could pass a regexp into data.split() as described here.
I'm not great with regexp but in this case something like this would work:
var tempArr = [];
myArray = data.split(/,|-| |\./);
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] !== "") {
tempArr.push(myArray[i]);
}
}
myArray = tempArr;
console.log(myArray);
I'm sure there's probably a way to discard empty strings from the array in the regexp without needing a loop but I don't know it - hopefully a helpful start though.
Here you go:
var data = ["- This, a sample string."];
var delimiters=[" ",".","-",","];
for (var i=0; i < delimiters.length; i++) {
var tmpArr = [];
for (var j = 0; j < data.length; j++) {
var parts = data[j].split(delimiters[i]);
for (var k = 0; k < parts.length; k++) {
if (parts[k]) {
tmpArr.push(parts[k]);
}
};
}
data = tmpArr;
}
console.log("info","String split using delimiters is - ", data);
Check for string length > 0 before doing a concat , and not != 1.
Zero length strings are getting appended to your array.

javascript split without losing first element (not RegEx)

I have a string containing ones and zeros split by "," and ";".
var x = "1,1,0;1,0,0;1,1,1;"; x.split(";");
This wil output an array with just two strings: 1,0,0 and 1,1,1.
What I want is to put all of these numbers in a two dimensional array:
1 1 0
1 0 0
1 1 1
If there is a smarter way than just split the string, please let me know.
Otherwise, please tell me how to fix the problem above.
You need to put quotes around your string.
Commentors are correct, your array contains all 3 strings. did you forget that array indices start at 0, not 1?
x.split does not modify x, it returns an array
You probably want something like this
var str = "1,1,0;1,0,0;1,1,1";
var arr = str.split(";");
for (var i = 0, len = arr.length; i < len; i++)
{
arr[i] = arr[i].split(",");
}
and to verify the result
for (var i = 0, len = arr.length; i < len; i++)
{
for (var j = 0, len2 = arr[i].length; j < len2; j++)
{
document.write(arr[i][j] + " | ");
}
document.write("<br>");
}
given the string:
var x = "1,1,0;1,0,0;1,1,1";
you can get a two dimensional array of zeros and ones this way:
var st = x.split(";")
var twoDimensionalArray = st.map(function(k){
return k.split(",");
});
of course, thanks to JS method chaining, you can do the whole thing this way:
var twoDimTable = x.split(";").map(function(k){
return k.split(",");
});
the result:
[
["1","1","0"],
["1","0","0"],
["1","1","1"]
]
well, to get the result as
[
[1,1,0],
[1,0,0],
[1,1,1]
]
you can do a loop and for each value k within the array do k = +k;
and you will get numbers instead of strings. However, JavaScript will do the casting
for you when you use these values within an operation with a number.

Categories

Resources