How can I concatenate an array of numbers into 1 cascading number?

How do I join this array to give me the expected result in as few steps as possible?

var x = [31,31,3,1]
//expected output: x = 313131;

      

+6


source to share


6 answers


Use array method join

. join

concatenates the elements of the array into a string and returns a string. The default delimiter is a comma (,). The separator here must be an empty string.



var  x = [31,31,3,1].join("");

      

+5


source


I can't think of anything else but

+Function.call.apply(String.prototype.concat, x)

      

or if you insist

+''.concat.apply('', x)

      

In ES6:

+''.concat(...x)

      

Usage 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 like a string, always a good approach.

+String.prototype.replace.call(x, /,/g, '')

      

There may be other ways. Perhaps a Google search on "javascript array concatenation" will trigger some obscure function that concatenates the array elements.

+4


source


Javascript join () will give expected output like string

. If you want it to be like 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(''))

      

+2


source


Try join () like this

var x = [31,31,3,1]
var y = x.join('');
alert(y);
      

Run code


0


source


Try below.

var x = [31,31,3,1]
var teststring = x.join("");

      

-2


source


This will work

var x = [31,31,3,1];
var result = x.join("");

      

-2


source







All Articles