How to Merge/Combine Arrays using JavaScript ? - GeeksforGeeks

01 Jul, 2020
There are many ways of merging arrays in JavaScript. We will discuss two problem statements that are commonly encountered in merging arrays:
Merge without removing duplicate elements.Merge after removing the duplicate elements.
Merge without removing duplicate elements.
Merge after removing the duplicate elements.
Merge without removing duplicate elements: We will first begin with three arrays and merge them. Later, we will generalize it for an indefinite number of arrays.
The three arrays are stated below:let nums1 = [1, 2, 3, 4]let nums2 = [3, 4, 5, 6]let nums3 = [5, 6, 7, 8]
We have to merge them so the our new array becomes:
combinedNums = [1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]
Using concat() Method: The concat() method accept arrays as arguments and returns the merged array.<script>      // Elements of nums2 and nums3 concatenated    // with elements of nums1 and returns the     // combined array - combinedSum array    let combinedNums = nums1.concat(nums2, nums3);      // More readable form    let combinedNums = [].concat(nums1, nums2, nums3);      console.log(combinedNums);</script>Output:[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]Using spread operator: Spread operator spreads the value of the array into its constituent elements.<script>    let combinedNums = [...nums1, ...nums2, ...nums3];      console.log(combinedNums);</script>Output:[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]Using push() Method: The push() method is used with spread operator to pushes the elements of arrays into the existing array. It is especially helpful when we need to append a value to an existing array and need not return a new array.Note: If spread operator is not used, then arrays as a whole are appended.<script>    nums1.push(...nums2, ...nums3);    console.log(nums1);      // If spread operator is not used    nums1.push(nums2, nums3);    console.log(nums1);</script>Output:first log: [1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]
second log: [1, 2, 3, 4, [3, 4, 5, 6], [5, 6, 7, 8]]

Using concat() Method: The concat() method accept arrays as arguments and returns the merged array.<script>      // Elements of nums2 and nums3 concatenated    // with elements of nums1 and returns the     // combined array - combinedSum array    let combinedNums = nums1.concat(nums2, nums3);      // More readable form    let combinedNums = [].concat(nums1, nums2, nums3);      console.log(combinedNums);</script>Output:[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]
<script>      // Elements of nums2 and nums3 concatenated    // with elements of nums1 and returns the     // combined array - combinedSum array    let combinedNums = nums1.concat(nums2, nums3);      // More readable form    let combinedNums = [].concat(nums1, nums2, nums3);      console.log(combinedNums);</script>
Output:
[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]
Using spread operator: Spread operator spreads the value of the array into its constituent elements.<script>    let combinedNums = [...nums1, ...nums2, ...nums3];      console.log(combinedNums);</script>Output:[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]
<script>    let combinedNums = [...nums1, ...nums2, ...nums3];      console.log(combinedNums);</script>
Output:
[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]
Using push() Method: The push() method is used with spread operator to pushes the elements of arrays into the existing array. It is especially helpful when we need to append a value to an existing array and need not return a new array.Note: If spread operator is not used, then arrays as a whole are appended.<script>    nums1.push(...nums2, ...nums3);    console.log(nums1);      // If spread operator is not used    nums1.push(nums2, nums3);    console.log(nums1);</script>Output:first log: [1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]
second log: [1, 2, 3, 4, [3, 4, 5, 6], [5, 6, 7, 8]]

Note: If spread operator is not used, then arrays as a whole are appended.
<script>    nums1.push(...nums2, ...nums3);    console.log(nums1);      // If spread operator is not used    nums1.push(nums2, nums3);    console.log(nums1);</script>
Output:
first log: [1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8]
second log: [1, 2, 3, 4, [3, 4, 5, 6], [5, 6, 7, 8]]

We will now generalize this for merging of an indefinite number of arrays:Our function mergeArrays accepts any number of arrays as arguments (rest operator). We will iterate through each array with forEach loop and add it into our final array: mergedArray.
Below are the implementations using concat, spread operator, and push method:
Using array.concat() method:<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];          function mergeArrays(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = mergedArray.concat(array)        });          return mergedArray;    }      console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]Using spread operator:<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];          function mergeArrays(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          return mergedArray;    }      console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]Using Array.push() Method:<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];          function mergeArrays(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray.push(...array)        });          return mergedArray;    }      console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]Merging and removing duplicate elements: Consider the following three approaches for doing this:Using set() method: Here, we spread the mergedArray elements into our set. Set stores unique items and removes duplicates. We then spread elements in the set into a new array and return that array having merged non-duplicate elements.<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];         function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          return [...new Set([...mergedArray])];    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using filter() Method: In this approach, we filter out elements of the mergedArray on the basis of their first occurrence in the array. We check whether the item occurs first by taking it’s first index with the help of indexOf method.<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];          function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          const mergedUnique = mergedArray            .filter((item, index) =>                 mergedArray.indexOf(item) === index);        return mergedUnique;    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using Array reduce() Method: In this approach, we take noDuplicates array as our accumulator. An item is appended in this array if it is not already present in the noDuplicates array. If an item is already present, we simply return the current array for the next iteration.<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];          function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          const mergedUnique = mergedArray           .reduce((noDuplicates, item) => {            if (noDuplicates.includes(item)) {                return noDuplicates;            }              else {                return [...noDuplicates, item];            }        }, [])          return mergedUnique;    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]My Personal Notes
arrow_drop_upSave
Using array.concat() method:<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];          function mergeArrays(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = mergedArray.concat(array)        });          return mergedArray;    }      console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]
<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];          function mergeArrays(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = mergedArray.concat(array)        });          return mergedArray;    }      console.log(mergeArrays(nums1, nums2));</script>
Output:
[1, 2, 3, 4, 3, 4, 5, 6]
Using spread operator:<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];          function mergeArrays(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          return mergedArray;    }      console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]
<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];          function mergeArrays(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          return mergedArray;    }      console.log(mergeArrays(nums1, nums2));</script>
Output:
[1, 2, 3, 4, 3, 4, 5, 6]
Using Array.push() Method:<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];          function mergeArrays(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray.push(...array)        });          return mergedArray;    }      console.log(mergeArrays(nums1, nums2));</script>Output:[1, 2, 3, 4, 3, 4, 5, 6]Merging and removing duplicate elements: Consider the following three approaches for doing this:Using set() method: Here, we spread the mergedArray elements into our set. Set stores unique items and removes duplicates. We then spread elements in the set into a new array and return that array having merged non-duplicate elements.<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];         function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          return [...new Set([...mergedArray])];    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using filter() Method: In this approach, we filter out elements of the mergedArray on the basis of their first occurrence in the array. We check whether the item occurs first by taking it’s first index with the help of indexOf method.<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];          function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          const mergedUnique = mergedArray            .filter((item, index) =>                 mergedArray.indexOf(item) === index);        return mergedUnique;    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using Array reduce() Method: In this approach, we take noDuplicates array as our accumulator. An item is appended in this array if it is not already present in the noDuplicates array. If an item is already present, we simply return the current array for the next iteration.<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];          function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          const mergedUnique = mergedArray           .reduce((noDuplicates, item) => {            if (noDuplicates.includes(item)) {                return noDuplicates;            }              else {                return [...noDuplicates, item];            }        }, [])          return mergedUnique;    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]My Personal Notes
arrow_drop_upSave
<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];          function mergeArrays(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray.push(...array)        });          return mergedArray;    }      console.log(mergeArrays(nums1, nums2));</script>
Output:
[1, 2, 3, 4, 3, 4, 5, 6]
Merging and removing duplicate elements: Consider the following three approaches for doing this:
Using set() method: Here, we spread the mergedArray elements into our set. Set stores unique items and removes duplicates. We then spread elements in the set into a new array and return that array having merged non-duplicate elements.<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];         function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          return [...new Set([...mergedArray])];    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using filter() Method: In this approach, we filter out elements of the mergedArray on the basis of their first occurrence in the array. We check whether the item occurs first by taking it’s first index with the help of indexOf method.<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];          function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          const mergedUnique = mergedArray            .filter((item, index) =>                 mergedArray.indexOf(item) === index);        return mergedUnique;    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]Using Array reduce() Method: In this approach, we take noDuplicates array as our accumulator. An item is appended in this array if it is not already present in the noDuplicates array. If an item is already present, we simply return the current array for the next iteration.<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];          function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          const mergedUnique = mergedArray           .reduce((noDuplicates, item) => {            if (noDuplicates.includes(item)) {                return noDuplicates;            }              else {                return [...noDuplicates, item];            }        }, [])          return mergedUnique;    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]
Using set() method: Here, we spread the mergedArray elements into our set. Set stores unique items and removes duplicates. We then spread elements in the set into a new array and return that array having merged non-duplicate elements.<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];         function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          return [...new Set([...mergedArray])];    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]
<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];         function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          return [...new Set([...mergedArray])];    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
Using filter() Method: In this approach, we filter out elements of the mergedArray on the basis of their first occurrence in the array. We check whether the item occurs first by taking it’s first index with the help of indexOf method.<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];          function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          const mergedUnique = mergedArray            .filter((item, index) =>                 mergedArray.indexOf(item) === index);        return mergedUnique;    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]
<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];          function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          const mergedUnique = mergedArray            .filter((item, index) =>                 mergedArray.indexOf(item) === index);        return mergedUnique;    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
Using Array reduce() Method: In this approach, we take noDuplicates array as our accumulator. An item is appended in this array if it is not already present in the noDuplicates array. If an item is already present, we simply return the current array for the next iteration.<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];          function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          const mergedUnique = mergedArray           .reduce((noDuplicates, item) => {            if (noDuplicates.includes(item)) {                return noDuplicates;            }              else {                return [...noDuplicates, item];            }        }, [])          return mergedUnique;    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>Output:[1, 2, 3, 4, 5, 6, 7, 8]
<script>    let nums1 = [1, 2, 3, 4];    let nums2 = [3, 4, 5, 6];    let nums3 = [5, 6, 7, 8];          function mergeNoDuplicates(...arrays) {        let mergedArray = [];          arrays.forEach(array => {            mergedArray = [...mergedArray, ...array]        });          const mergedUnique = mergedArray           .reduce((noDuplicates, item) => {            if (noDuplicates.includes(item)) {                return noDuplicates;            }              else {                return [...noDuplicates, item];            }        }, [])          return mergedUnique;    }      console.log(mergeNoDuplicates(nums1, nums2, nums3));</script>
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript