Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow to Merge/Combine Arrays using JavaScript ?

How to Merge/Combine Arrays using JavaScript ?

There are many ways of merging arrays in JavaScript. We will discuss two problem statements that are commonly encountered in merging arrays:

  1. Merge without removing duplicate elements.
  2. 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]
  1. 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]
  2. 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]
  3. 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]]
    

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:

  1. 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]
  2. 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]
  3. 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]
  4. Merging and removing duplicate elements: Consider the following three approaches for doing this:

    1. 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]
    2. 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]
    3. 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]

RELATED ARTICLES

Most Popular

Recent Comments