Let us say you have the following two arrays.
var array1 = [1, 2]; var array2 = [2, 3];
Let us say you want to merge these two arrays meaning include all the elements present in each array while removing duplicate elements. You can easily do this using concat function available in each array since ES5.
var array3 = array1.concat(array2); console.log(array3); //[1, 2, 3]
Alternatively, you can also use something called destructuring, available since ES6. But in this case, your result will contain duplicates. Here is an example, we need to prefix each array with three dots (…)
var array3 = [...array1, ...array2]; console.log(array3); //[1, 2, 2, 3]
If you wish to remove duplicates, you can create a set out of the above result, and then convert the set back into an array, as shown below.
var array3 = [...new Set([...array1 ,...array2])]; console.log(array3); //[1, 2, 3]
var array4 = array1.concat(array2, array3);
Here is an example to merge 3 arrays using array destructuring.
var array4 = [...array1, ...array2, ...array3];
You can also use third-party libraries like jQuery or Underscore to merge arrays.
How to Persist Variables Through Page Reload
How to Scroll to Element Using jQuery