skip to Main Content

I have three arrays in which first index is same, so i want to merge all three array into one array based on first index element

Input:

[[1, 'A'], [2, 'B'], [3, 'C']];
[[1, 'D'], [2, 'E'], [3, 'F']];
[[1, 'G'], [2, 'H'], [3, 'I']];

Expected output

[ 
  [ 1, 'A', 'D', 'G' ], 
  [ 2, 'B', 'E', 'H' ], 
  [ 3, 'C', 'F', 'I' ] 
]

My code:

function mergeArrays(arrays) {
  const mergedMap = new Map();

  for (const array of arrays) {
    for (const item of array) {
      const key = item[0];
      if (!mergedMap.has(key)) {
        mergedMap.set(key, [key]);
      }
      mergedMap.get(key).push(...item.slice(1));
    }
  }

  const mergedArray = Array.from(mergedMap.values());

  return mergedArray;
}

const array1 = [[1, 'A'], [2, 'B'], [3, 'C']];
const array2 = [[1, 'D'], [2, 'E'], [3, 'F']];
const array3 = [[1, 'G'], [2, 'H'], [3, 'I']];

const mergedResult = mergeArrays([array1, array2, array3]);
console.log(mergedResult);

Would you please suggest any better solution?

Please note: for the simplicity i have make first index as number but in my case it is a Date object.

2

Answers


  1. Your code seems to work fine, but there are some possible improvements you can make:

    • You can use the Array.prototype.reduce method to iterate over the arrays and create the merged map, instead of using a for loop. This will make your code more concise and functional.
    • You can use the spread operator (...) to simplify the creation of the merged array from the map values, instead of using the Array.from method.
    • You can use the Array.prototype.concat method to combine the items from different arrays, instead of using the Array.prototype.push and Array.prototype.slice methods. This will avoid mutating the original arrays and creating intermediate arrays.

    Here is an example of how you can rewrite your code using these suggestions:

    function mergeArrays(arrays) {
      // Use reduce to create a map of keys and merged values
      const mergedMap = arrays.reduce((map, array) => {
        // Iterate over each item in the array
        for (const item of array) {
          const key = item[0];
          // If the map does not have the key, create an array with the key
          if (!map.has(key)) {
            map.set(key, [key]);
          }
          // Concatenate the rest of the item to the existing array in the map
          map.set(key, map.get(key).concat(item.slice(1)));
        }
        // Return the updated map
        return map;
      }, new Map());
    
      // Use spread operator to create an array from the map values
      const mergedArray = [...mergedMap.values()];
    
      return mergedArray;
    }
    
    const array1 = [[1, 'A'], [2, 'B'], [3, 'C']];
    const array2 = [[1, 'D'], [2, 'E'], [3, 'F']];
    const array3 = [[1, 'G'], [2, 'H'], [3, 'I']];
    
    const mergedResult = mergeArrays([array1, array2, array3]);
    console.log(mergedResult);
    
    Login or Signup to reply.
  2. lodash version as below

    const _ = require('lodash');
    function mergeArrays(arrays) {
      return _.chain(arrays)
        .flatten()
        .groupBy((item) => item[0])
        .mapValues(L1=>_.uniq(_.flatten(L1)))
        .values()
        .value();
    }
    
    const array1 = [[1, 'A'], [2, 'B'], [3, 'C']];
    const array2 = [[1, 'D'], [2, 'E'], [3, 'F']];
    const array3 = [[1, 'G'], [2, 'H'], [3, 'I']];
    
    const mergedResult = mergeArrays([array1, array2, array3]);
    console.log(mergedResult);
    
    //output as you want
    [ 
      [ 1, 'A', 'D', 'G' ], 
      [ 2, 'B', 'E', 'H' ], 
      [ 3, 'C', 'F', 'I' ] 
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search