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;
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;
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("");
I can't think of anything other than
+Function.call.apply(String.prototype.concat, x)
or, if you insist
+''.concat.apply('', x)
In ES6:
+''.concat(...x)
Using reduce
:
+x.reduce((a, b) => a + b, '');
Or if you prefer
x.reduce(Function.call.bind(String.prototype.concat), '')
Another idea is to manipulate the array as a string, always a good approach.
+String.prototype.replace.call(x, /,/g, '')
There may be other ways. Perhaps a Google search on "join array javascript" would turn up some obscure function which joins elements of an array.
Javascript join() will give you the expected output as string
. If you want it as a number
, do this:
var x = [31,31,3,1];
var xAsString = x.join(''); // Results in a string
var xAsNumber = Number(x.join('')); // Results in a number, you can also use +(x.join(''))
Your question asks for a number, most of the answers above are going to give you a string. You want something like this.
const number = Number([31,31,3,1].join(""));
Try join() as follows
var x = [31,31,3,1]
var y = x.join('');
alert(y);
Try below.
var x = [31,31,3,1]
var teststring = x.join("");
This will work
var x = [31,31,3,1];
var result = x.join("");