Merge two arrays with alternating Values

前端 未结 9 2202
南笙
南笙 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));
    

提交回复
热议问题