Search code examples
javascriptarraysarray-merge

Efficiently merge two arrays by distribute values evenly


I have seen many question/answer subject to merge two array by alternating Values. they are working like this:

let array1 = ["a", "b", "c", "d"];
let array2 = [1, 2];

let outcome = ["a",1 ,"b", 2, "c", "d"] 

but i want output to be more efficient with even distribution of value based on array size.

expected outcome = ["a","b", 1, "c", "d", 2] 

other scenario

let array2 = [1];
expected outcome = ["a","b", 1, "c", "d"] 

what should be the best way to achieve this sort of merging?


Solution

  • Find the ratio of the two arrays' lengths, longest.length/shortest.length and then take that many from the longest for every one in the shortest.

    let array1 = ["a", "b", "c", "d", "e"];
    let array2 = [1, 2];
    
    const evenDistribute = (array1, array2) => {
      const longest = array1.length > array2.length ? array1 : array2;
      const shortest = array1.length > array2.length ? array2 : array1;
      const ratio = Math.floor(longest.length / shortest.length);
      const results = [];
      for (let i = 0; i < shortest.length; i++) {
        for (let j = 0; j < ratio; j++) {
          results.push(longest[i * ratio + j]);
        }
        results.push(shortest[i]);
      }
      // Grab any that are left over
      for (let i = longest.length - (longest.length % shortest.length); i < longest.length; i++) {
        results.push(longest[i]);
      }
      return results;
    }
    
    console.log(evenDistribute(array1, array2));