Imagine that I have create an array as follows:
var arr1 = ['one', 'two', 'three'];
I now want to create another array like this:
var arr2 = [arr1, 'four', 'five']
This is now the contents of arr2:
[Array(3), "four", "five"]
That is NOT what I want. I would like the contents to look like this:
['one', 'two', 'three', 'four', 'five']
How can I do that?
Note, I'm not looking for a function like concat, but rather a way to list arr1 as an item in arr2 in such a way that all the items in arr1 will be added as individual items in arr2 (I hope that made sense).
Thanks for any help that you can offer.
4 Answers 4
With ES6 spread syntax ... you can do exactly that.
The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.
var arr1 = ['one', 'two', 'three'];
var arr2 = [...arr1, 'four', 'five']
console.log(arr2)
4 Comments
unshift like this jsfiddle.net/Lg0wyt9u/1922 it will add whole array and not each element, but if you use it with spread syntax like this jsfiddle.net/Lg0wyt9u/1923 then why use unshiftUpdate: Now the question is changed, this solution no long supplies the question.
You can use concat for this:
var arr1 = ['one', 'two', 'three'];
var arr2 = arr1.concat(['four', 'five', 'six']);
Which outputs
["one", "two", "three", "four", "five", "six"]
Comments
If you're using new versions of JS. You may do it just like this:
var
array1 = [1,2,3],
array2 = [3, 4, 5];
array2.unshift(...array1);
// array2 = [1,2,3,4,5,6]
// array1 = [1, 2, 3]
Comments
Ways to achieve this :
1. ES6 Array.of() method : It will create a new Array with a variable number of arguments, regardless of number or type of the arguments.
const arr1 = ['one', 'two', 'three'];
const arr2 = Array.of(...arr1, 'four', 'five');
console.log(arr2);
2. Using Array.concat() method : This method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
var arr1 = ['one', 'two', 'three'];
var arr2 = arr1.concat(['four', 'five']);
console.log(arr2);
3. Using ES6 Array.from() method : It also creates a new Array instance from an array-like or iterable object.
const arr1 = ['one', 'two', 'three'];
Array.from(['four', 'five'], item => arr1.push(item));
console.log(arr1);
arr2 = [...arr1, 'four', 'five']