I have 2 arrays, array1
and array2
. Both have some values but not the same length.
I want to concatenate array2
into array1
.
I have tried this but it is not working:
array1 = array1.concat(array2);
I have 2 arrays, array1
and array2
. Both have some values but not the same length.
I want to concatenate array2
into array1
.
I have tried this but it is not working:
array1 = array1.concat(array2);
To just merge the arrays without removing duplicates
ES5 version use Array.concat:
var array1 = ["foo","bar"];
var array2 = ["bar", "biz"];
var array3 = array1.concat(array2);
ES6 version use destructuring
const array1 = ["foo","bar"];
const array2 = ["bar", "biz"];
const array3 = [...array1, ...array2];
Result
// [ 'foo', 'bar', 'bar', 'biz' ]
Merge the arrays WITH removing duplicates
var array1 = ['foo', 'bar', 'biz'], array2 = ['delta', 'bar', 'foo', 'tango'];
var array3 = array1.concat(array2.filter(function (item) {
return array1.indexOf(item) < 0;
}));
Result:
// ["foo", "bar", "biz", "delta", "tango"]