convert array value to string value with javascript - 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.

Related

Fastest way to convert a string into a Float32Array

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

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

Concatenate array into string

I have this:
var myarray = [];
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
And I want to get the string:
"first":"$firstelement","second": "$secondelement"
How can I do it?
What you have is invalid (even if it works), arrays don't have named keys, but numeric indexes.
You should be using an object instead, and if you want a string, you can stringify it as JSON
var myobject = {};
myobject["first"] = "$firstelement";
myobject["second"] = "$secondelement";
var str = JSON.stringify(myobject);
console.log(str)
First of all, you'd want to use an object instead of an array:
var myarray = {}; // not []
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
The easiest way, then, to achieve what you want is to use JSON:
var jsonString = JSON.stringify(myarray);
var arrayString = jsonString.slice(1, -1);
JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
var myarray = {};
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
console.log(JSON.stringify(myarray));
Use JSON.strinify()
JSON.stringify(item)

Match two Arrays as Object of Array

I have two arrays and I need to make it as object of array
var arr1 = [1,2,3,4,5]
var arr2 = [a,b,c]
Is there any possibility to change the array to this format[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
Could someone help me?
Try this code:
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = arr2.reduce(function(obj, item) {
obj[item] = arr1.slice(); // or = arr1 to keep the reference
return obj;
}, {});
console.log(result); // {"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
You have 2 cases:
To create clones of the array use result[item] = arr1.slice();
To keep the reference to the same array use result[item] = arr1;
Check more about the reduce() method.
I am assuming you need a object like this
{"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
So you can do it like this.
var arr1 = [1,2,3,4,5]
var arr2 = ["a","b","c"];
var result={}
arr2.map(function(k){
result[k]=arr1;
})
console.log(result);
But here I am giving values of keys as arr1 reference so if arr1 will change value of keys in result will also change.
Is there any possibility to change the array to this
formate[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
This is neither an array format nor a valid JSON literal, so this format could only be a string.
Assuming that you are looking for a string in the format you have specified
var output = "[" + arr2.map(function(value){return value+",{" + arr1.join(",") + "}"}).join("],[") + "]";
Use forEach to iterate through List and get your desired result.
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = {} // Result: Object of Array
arr2.forEach(function(val, index) {
result[val] = arr1;
})
I hope this is easy to understand :)

Categories

Resources