Is there a method that would join all array elements into one element?
For example:
var array = [1,2,3];
// array = [123];
Is there a method that would join all array elements into one element?
For example:
var array = [1,2,3];
// array = [123];
You could reduce the array.
var array = [1, 2, 3],
result = array.reduce(([a], b) => [(a || 0) * 10 + b], []);
console.log(result);
A shorter one as proposed by T. J. Crowder in the comments.
var array = [1, 2, 3],
result = [array.reduce((a, b) => a * 10 + b, 0)];
console.log(result);
Here's a possible solution using .join().
The array.join() method is an inbuilt function in JavaScript which is used to join the elements of an array into a string.The elements of the string will be separated by a specified separator and its default value is comma(, ).
Note that by passing the empty string to join you can get the concatenation of all elements of the array.
In other words join('') will also remove the extra commas.
The final result of this process is then converted to a number using parseInt, I think this is an easy solution to understand for beginners.
// Expected result is an array like this
// var newArray = [123];
var array = [1,2,3];
var newArray = [parseInt(array.join(''))];
console.log(newArray);
Bonus
I see that many users here suggested the unary operator + instead of parseInt.
There is an interesting answer and discussion on the topic here on Stackoverflow.
With array.join you can can join all elements as string and then use Number or parseInt function to convert it as number.
const array = [1,2,3];
const result = [Number(array.join(''))];
// const result = [parseInt(array.join(''), 10)];
var result=0;
var array = [1,2,3];
for(i=0;i<array.length;i++){
var a = Math.pow(10,array.length-i-1)
result += array[i]*a
}
Use join
method
var array = [1,2,3];
var joinedArray = array.join('')
while (array.length) {
array.pop();
}
array.push(parseInt(joinedArray));
console.log(array);
Explanation:
join('')
will concatenate all the elements in an array into a string.
+
will convert it into a number.
let array = [1, 2, 3];
console.log([+array.join('')]);
You also can do it like...
var array = [1,2,3];
var join="";
array_size = array.length;
for (let i=0 ; i<=array_size ; i++)
join += array[i];
that will return a string not a number.
You can convert it to number using join = Number(join);
You can join it like this
var array = [1,2,3];
var joined = array.join();
joined = joined.replace (/,/g, "");
console.log(joined);