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;
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(""));
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("");
This will work
var x = [31,31,3,1];
var result = x.join("");
Try below.
var x = [31,31,3,1]
var teststring = x.join("");
Try join() as follows
var x = [31,31,3,1]
var y = x.join('');
alert(y);
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.