Fastest way to convert a string into a Float32Array - javascript

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);

Related

String into multiple string in an array

I have not been coding for long and ran into my first issue I just can not seem to figure out.
I have a string "XX|Y1234$ZT|QW4567" I need to remove both $ and | and push it into an array like this ['XX', 'Y1234', 'ZT', 'QW4567'].
I have tried using .replace and .split in every way I could like of
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for(i = o; i <array.length; i++)
var loopedArray = array[i].split("|")
loopedArray.push(array2);
}
I have tried several other things but would take me awhile to put them all down.
You can pass Regex into .split(). https://regexr.com/ is a great tool for messing with Regex.
// Below line returns this array ["XX", "Y1234", "ZT", "QW4567"]
// Splits by $ and |
"XX|Y1234$ZT|QW4567".split(/\$|\|/g);
Your code snippet is close, but you've messed up your variables in the push statement.
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for (i = 0; i < array.length; i++) {
var loopedArray = array[i].split("|")
array2.push(loopedArray);
}
array2 = array2.flat();
console.log(array2);
However, this can be rewritten much cleaner using flatMap. Also note the use of let instead of var and single quotes ' instead of double quotes ".
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array
.split('$')
.flatMap(arrayI => arrayI.split('|'));
console.log(array2);
And lastly, split already supports multiple delimiters when using regex:
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array.split(/[$|]/);
console.log(array2);
You can do this as follows:
"XX|Y1234$ZT|QW4567".replace('$','|').split('|')
It will produce the output of:
["XX", "Y1234", "ZT", "QW4567"]
If you call the split with two parameters | and the $ you will get an strong array which is splittend by the given characters.
var array = "XX|Y1234$ZT|QW4567";
var splittedStrings = array.Split('|','$');
foreach(var singelString in splittedStrings){
Console.WriteLine(singleString);
}
the output is:
XX
Y1234
ZT
QW4567

Javascript - How to split a string into a nested array?

I know I can use split function to transform a string to an array but how can a string be split twice to produce a nested array?
I expected this would be sufficent but it does not produce the desired output.
var myString = "A,B,C,D|1,2,3,4|w,x,y,z|"
var item = myString.split("|");
var array = [item.split(",")];
Would it be more optimal to use a for each loop?
EXPECTED OUTPUT
var array = [
["A","B","C","D"],
["1","2","3","4"],
["w","x","y","z"],
];
Once you've split on |, use .map to account for the nesting before calling .split again. There's also an empty space after the last |, so to exclude that, filter by Boolean first:
const myString = "A,B,C,D|1,2,3,4|w,x,y,z|";
const arr = myString
.split('|')
.filter(Boolean)
.map(substr => substr.split(','));
console.log(arr);
Or you could use a regular expression to match anything but a |:
const myString = "A,B,C,D|1,2,3,4|w,x,y,z|";
const arr = myString
.match(/[^|]+/g)
.map(substr => substr.split(','));
console.log(arr);
var myString = "A,B,C,D|1,2,3,4|w,x,y,z"
var item = myString.split("|");
var outputArr = item.map(elem => elem.split(","));
console.log(outputArr);

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

Get number from the string JS / Lodash / TypeScript

I have a link that comes in as a string, for example:
let data = [
'/api/customer’,
'/api/customer/123’,
'/api/customer/123/details’
];
I need to extract the numeric ID if there is one. The only way I found is trough _.isNaN():
const myStrArray = type.split('/');
const numericsArray = _.filter(myStrArray, urlPart => !_.isNaN(parseInt(urlPart, 10)));
const id = numericsArray[0]; // undefined/123
Is there a better way to do this?
You can iterate the array with Array.flatMap() (or lodash _.flatMap()), and use String.match() with a RegExp to get a sequence of numbers.
Note: this RegExp assumes that these are the only numbers in the string. You might want to fine tune it, if there's a possibility for other numbers.
let data = [
'/api/customer',
'/api/customer/123',
'/api/customer/123/details'
];
const result = data.flatMap(str => str.match(/\d+/));
console.log(result);
User regex and Array#map and Array#flat like so. You need to use ||[] in case a number was not found.
const data = [
'/api/custome',
'/api/customer/123',
'/api/customer/123/details'
];
const res = data.map(a=>a.match(/\d+/)||[]).flat();
console.log(res);

convert array value to string value with javascript

I have an array
let arr = [12,12,43,53,56,7,854,3,64,35,24,67]
i want the result back as string
let strArr = "12,12,43,53,56,7,854,3,64,35,24,67"
Please some one suggest me any solution
You can use toString() method:
let arr = [12,12,43,53,56,7,854,3,64,35,24,67];
arr = arr.toString();
console.log(arr);
console.log(typeof arr);
You can read more about this here.
One solution is to use join method.
The join() method joins the elements of an array into a string, and
returns the string.
let arr = [12,12,43,53,56,7,854,3,64,35,24,67]
let strArr = arr.join();
console.log(strArr);
Use Array.prototype.join().
The join() method joins all elements of an array (or an array-like object) into a string.
var a = [12,12,43,53,56,7,854,3,64,35,24,67];
a.join(); // '12,12,43,53,56,7,854,3,64,35,24,67'
JS type coercion is sometimes useful.
var arr = [12,12,43,53,56,7,854,3,64,35,24,67],
strArr = arr + ""; // <- "12,12,43,53,56,7,854,3,64,35,24,67"
Solution to this would be to use join()
let arr = [12,12,43,53,56,7,854,3,64,35,24,67]
let strArr = arr.join();
Second you be to use toString()
let arr = [12,12,43,53,56,7,854,3,64,35,24,67]
let strArr = arr.toString();
Because you want to join by a comma, they are basically identical, but join allow you to chose a value separator.

Categories

Resources