Merge two arrays with alternating Values

前端 未结 9 1991
南笙
南笙 2020-12-03 14:19

i would like to merge 2 arrays with a different length:

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

let outcome = [\"a\",1 ,\"b\", 2, \"         


        
相关标签:
9条回答
  • 2020-12-03 14:51

    A bit verbose solution that lets you choose which array goes first

    const a = ['a', 'b', 'c'];
    const b = [1, 4];
    const combineAlternatingArrays = (a, b) => {
      let combined = [];
      const [shorter, larger] = [a, b].sort((a, b) => a.length -b.length);
    
      shorter.forEach((item, i) => {
        combined.push(larger[i], item);
      })
      combined.push(...larger.slice(shorter.length));
    
      return combined;
    }
    console.log(combineAlternatingArrays(a, b));
    

    It is also possible to use a reduce, but the syntax is less clear in my opinnion.

    const a = ['a', 'b', 'c'];
    const b = [1, 4];
    const combineAlternatingArrays = (a, b) => {
      const [shorter, larger] = [a, b].sort((a, b) => a.length -b.length);
    
      return shorter.reduce(
        (combined, next, i, shorter) => {
          return (i === (shorter.length -1)) ? [...combined, larger[i], next, ...larger.slice(shorter.length)] : [...combined, larger[i], next];
        },
        []
      );
    }
    console.log(combineAlternatingArrays(a, b));
    
    0 讨论(0)
  • 2020-12-03 15:00

    Create an array of tuples. Each tuple contains 1 element from each array, flatten by spreading the array of tuples, and adding the leftover items from the arrays:

    const a1 = ["a", "b", "c", "d"];
    const a2 = [1,2];
    const l = Math.min(a1.length, a2.length);
    
    const merged = [].concat(...Array.from({ length: l }, (_, i) => [a1[i], a2[i]]), a1.slice(l), a2.slice(l));
      
    console.log(merged);

    0 讨论(0)
  • 2020-12-03 15:05

    Here's a modern solution that takes any number of arrays:

    const braidArrays = (...arrays) => {
      const braided = [];
      for (let i = 0; i < Math.max(...arrays.map(a => a.length)); i++) {
        arrays.forEach((array) => {
          if (array[i] !== undefined) braided.push(array[i]);
        });
      }
      return braided;
    };
    

    Note that you could change Math.max to Math.min to only include up to the shortest array.

    Here's a sample I/O:

    braidArrays(['a','b','c','d'], [1,2,3], [99,98,97,96,95]);
    // ['a', 1, 99, 'b', 2, 98, 'c', 3, 97, 'd', 96, 95]
    
    0 讨论(0)
  • 2020-12-03 15:09

    You can do:

    const array1 = ["a", "b", "c", "d"];
    const array2 = [1, 2];
    const mergeArrays = (a, b) => (a.length > b.length ? a : b)
      .reduce((acc, cur, i) => a[i] && b[i] ? [...acc, a[i], b[i]] : [...acc, cur], []);
    
    console.log(mergeArrays(array1, array2)); // ["a",1 ,"b", 2, "c", "d"]

    0 讨论(0)
  • 2020-12-03 15:11

    ONELINER: I assume that x=array1, y=array2, x and y can be arbitrary arr

    [...x,...y].reduce((l,c,i)=>(i<x.length&&l.push(x[i]),i<y.length&&l.push(y[i]),l),[])
    

    working example (for 3 cases)

    0 讨论(0)
  • 2020-12-03 15:12

    This can be done rather simply using a splicing function within reduce:

    function splicer(array, element, index) {
        array.splice(index * 2, 0, element);
        return array;
    }
    
    function weave(array1, array2) {
        return array1.reduce(splicer, array2.slice());
    }
    
    let array1 = ["a", "b", "c", "d"];
    let array2 = [1, 2];
    
    let outcome = weave(array1, array2);
    
    console.log(outcome);

    0 讨论(0)
提交回复
热议问题