How do I join this array to give me expected output in as few steps as possible?
var x = [31,31,3,1]
//expected output: x = 313131;
Definition and UsageThe concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.
The recommended solution is to use the std::copy from the <algorithm> header to concatenate two arrays. The idea is to allocate memory large enough to store all values of both arrays, then copy the values into the new array with std::copy .
Use array join
method.Join
joins the elements of an array into a string, and returns the string. The default separator is comma (,). Here the separator should be an empty string.
var x = [31,31,3,1].join("");
EDIT: To get the result as numeric
const x = +[31,31,3,1].join("");
or
const x = Number([31,31,3,1].join(""));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With