dadadodo
dadadodo

Reputation: 347

making a single number out of all the numbers in an Array

lets say we have an array var arr = [1,3,4,0]; how can I make a single number out of all the elements like so var number = 1340; I should be able to do operations on number. The number of elements in arr could vary

Upvotes: 1

Views: 773

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115242

Using Array#reduce method

console.log(
  [1, 3, 4, 0].reduce(function(sum, n, i) {
    return sum * 10 + n;
  })
)

Upvotes: 2

madox2
madox2

Reputation: 51881

Use Array.prototype.join(), and parseInt() function to convert string to number:

parseInt([1,3,4,0].join('')); // 1340

Upvotes: 4

Related Questions