A nested array of string to number - javascript

I'm looking to convert a nested array of the type string to type float, or alternatively parsing it from a text file. Format is something along the lines of this [45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]

The first step would be to create valid JSON from your string.
If your input will always follow the schema you showed us, you could just prepend and append brackets to the string. This is not a pretty solution though. You should first check if you can get valid JSON in the first place.
A solution could look like this, provided that the input string will always follow the format of "[float, float], [float, float]":
const input = "[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]";
// Add brackets in order to have valid JSON.
const arrayString = "[" + input + "]";
// Parse the string into an object.
const parsedArray = JSON.parse(arrayString);
// Flatten the nested array to get a one dimensional array of all values.
var flattenedArrays = [].concat.apply([], parsedArray);
// Do something with your values.
flattenedArrays.forEach(floatValue => console.log(floatValue));

You can use JSON.parse, if your numbers are actually numbers in a JSON (serialized without quotes).
let test = "[[3, 4.2], [5, 6]]";
let test2 = JSON.parse(test);
console.log(test2);
Otherwise you can simply convert your array of array of strings to array of array of numbers using + and some array mapping. :
let test = [["3", "4.2"], ["5", "6"]];
let test2 = test.map((x) => x.map((y) => +y));
console.log(test2);
Of course, you can combine both solutions if for some reason you don't control the input and have a JSON containing strings.

This thread shows you how to loop through an array of strings to convert it to an array of floats.

i hope this will work..
var input = [[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]]
var output = [];
input.forEach(o => {
o.forEach(s => parseFloat(s))
output.push(o);
})
console.log(output);

Related

How can i take the objects inside in the array?

I have this Result :
["572a2b2c-e495-4f98-bc0a-59a5617b488c", "2d50c44a-0f94-478b-91b6-bb0cd8287e70"]
But i would like to have only :
"572a2b2c-e495-4f98-bc0a-59a5617b488c", "2d50c44a-0f94-478b-91b6-bb0cd8287e70"
Is this Possible ?
I would like to delete the Array and only have the raw data from inside the Array
You can use join() and join the array of string with , also use map() to add "" around string
const arr = ["572a2b2c-e495-4f98-bc0a-59a5617b488c", "2d50c44a-0f94-478b-91b6-bb0cd8287e70"]
console.log(arr.map(x => `"${x}"`).join(','))
Array.prototype.toString() method will coerce all array elements to string type and give you the entire array as a single string with elements separated by comma:
const arr = ["572a2b2c-e495-4f98-bc0a-59a5617b488c", "2d50c44a-0f94-478b-91b6-bb0cd8287e70"];
const arr_toString = arr.toString();
// "572a2b2c-e495-4f98-bc0a-59a5617b488c,2d50c44a-0f94-478b-91b6-bb0cd8287e70"
If you want the array as single string separated by comma and each element wrapped by "":
const arr = ["572a2b2c-e495-4f98-bc0a-59a5617b488c", "2d50c44a-0f94-478b-91b6-bb0cd8287e70"];
const wanted_result = arr.map(elm => `"${elm}"`).toString();
// "572a2b2c-e495-4f98-bc0a-59a5617b488c","2d50c44a-0f94-478b-91b6-bb0cd8287e70"
Array.prototype.map() executes whatever function you supply on all the elements of the array and return the returned value of the function. So the function I used is:
elm => `"${elm}"` - which takes each elm and return it wrapped by ""

Array values to a string in loop

I have an object (key value pair) looks like this
I want to get a string of '[100000025]/[100000013]'
I can't use var str = OBJ[0].PC + OBJ[1].PC (which gives me '100000025100000013')
because I need the bracket structure.
The number of items can vary.
Added >> Can it be done without using arrow function?
const string = array.map(({PC}) => `[${PC}]`).join('/')
You could map every string to the string wrapped in brackets, then join that by slashes.
You can use a map() and a join() to get that structure. - this is hte same solution as Puwka's = but without the template literal.
var data = [
{am: 1, ct: "", pc: "1000000025"},
{am: 2, ct: "", pc: "1000000013"}
];
let newArr = data.map(item => "[" + item.pc +"]");
console.log(newArr.join("/")); // gives [1000000025]/[1000000013]
You can always use classic for in loop
let arr = [{PC:'1000'},{PC:'10000'}]
let arrOut = [];
for(let i = 0; i < arr.length; i++) {
arrOut.push('[' + arr[i].PC + ']');
}
now the arrOut is equal ["[1000]", "[10000]"] what we need is to convert it to a string and add '/' between items.
let str = arrOut.join('/');
console.log(str) // "[1000]/[10000]"
So you need a string in the format of: xxxx/yyyyy from a complex object array.
const basedata = [...];
const result = basedata.map( item => `[${item.PC}]` ).join('/')
so i will explain it now. The map function will return a new array with 1 entry per item. I state that I want PC, but i added some flavor using ticks to inject it inbetween some brackets. At this point it looks like: ["[1000000025]","[100000013]"] and then join will join the arrays on a slash, so it will turn into an array.
"[100000025]/[100000013]"
Now, this will expand based on the items in your basedata. So if you have 3 items in your basedata array, it would return:
"[10000000025]/[100000013]/[10000888]"
First if you want to divide the result then it will be better to change it into number and then just do the division.
Example
Number.parseInt("100000025")/Number.parseInt("100000013")
If you want to display it then better to use string interpolation
surround it with back tick
[${[0].PC}]/[${[1].PC}]
Hope this is what are you looking for

How do I convert an array inside an array to a string?

I'm new to programming. I am coding with javascript.
I want to convert an array with 3 arrays inside it to one single string and have spaces between each of the different arrays.
I want to turn this:
var myArray = [['example'], ['text'], ['hm']]
Into this:
var myString = 'example text hm'
I think you want that to be an array with []. If that's the case, this is a good use for reduce() combined with join() which will progressively build a concatenated array which you can then join:
let myArray = [['example'], ['text', 'text2'], ['hm']]
let str = myArray.reduce((all, arr) => all.concat(arr)).join(' ')
console.log(str)
Use nested for-each loops.
myString = "";
for each (row in myArray){
for each (column in row){
myString = myString + column;
}
}
In this specific case, you can use the standard Array.join(). This will invoke the sub-array's .toString() method. Usually it returns a string of the items, separated by commas, but Since you've got only a single item in each sub-array, you'll get that item in a string.
const myArray = [['example'], ['text'], ['hm']]
const result = myArray.join(' ')
console.log(result)
You can join them together using Array.join(' ')
const sentence = myArray.join(' ')
will return "example text hm"
The speech marks separated will keep the words separate and stop them joining together. If they are together it will join all the strings "exampletexthm"
I would also suggest that you use const or let instead of var. It can cause some issues. Article to look at

Filter array by content?

I'm trying to filter an array that is non-object based, and I need the filter to simply check each piece of the array for a specific string.
Say I have this array:
["http://mywebsite.com/search", "http://mywebsite.com/search", "http://yourwebsite.com/search"]
What I need to do is harvest the array in a way so that I get a new array that only contain those who start with http://mywebsite.com and not http://yourwebsite.com
In conclusion making this: ["http://mywebsite.com/search", "http://mywebsite.com/search", "http://yourwebsite.com/search"]
into this ["http://mywebsite.com/search", "http://mywebsite.com/search"]
You can filter the array using .filter() and .startsWith() method of String.
As from Docs:
The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.
Demo:
let data = ["http://mywebsite.com/search",
"http://mywebsite.com/search",
"http://yourwebsite.com/search"];
let result = data.filter(s => s.startsWith('http://mywebsite.com/'));
console.log(result);
As mentioned in your comment; if you wants to check multiple strings then you can try this:
let data = ["http://mywebsite.com/search",
"http://mywebsite.com/find",
"http://yourwebsite.com/search",
"http://yourwebsite.com/find"];
let strToMatch = ["http://mywebsite.com/search", "http://mywebsite.com/find"];
let result = data.filter(s1 => strToMatch.some(s2 => s2.startsWith(s1)));
console.log(result);
Docs:
String.prototype.startsWith()
Array.prototype.filter()
Arrow Functions
Use Array filter() method
You can make a simple function and pass that array of string and check what you want in it exist or not
var yourString = ["http://mywebsite.com/search", "http://mywebsite.com/search", "http://yourwebsite.com/search"];
function specificString(yourString ) {
return yourString === "http://mywebsite.com/search";
}
console.log(specificString(yourString));

cannot convert string in array format such as "[55]" to array

I receive the following from another server in my payload as query param:
"[55]"
Now I want to convert it to an array in JavaScript,
Here is what I do:
var termssValidation= JSON.parse(JSON.stringify(event.termsQuery));
But when I run the following:
for(var t in termssValidation ){
console.log(termssValidation[t]);
}
I get 3 lines as follows:
[
5
5
]
How can I convert the above to an array properly?
You need just to parse the JSON string.
console.log(JSON.parse('[55]'));
JSON.stringify is excess
let j = JSON.parse("[55]")
console.log(j)
The problem is the inner JSON.stringify().
This method converts the "[66]" into ""[66]"". JSON.parse then converts this string as if the inner quotes were escaped. So the result is the original string "[66]".
Because the String in javascript is an iterable you get the individual characters as the result of the iteration.
This is the solution to your problem:
var termssValidation= JSON.parse(event.termsQuery);
This code works!
let a = "[55]";
a = JSON.parse(a);
for (let i in a) {
console.log(a[i]); //55
}

Categories

Resources