Terse way to intersperse element between all elements in JavaScript array?

前端 未结 16 1005
终归单人心
终归单人心 2020-12-17 09:19

Say I have an array var arr = [1, 2, 3], and I want to separate each element by an element eg. var sep = \"&\", so the output is [1, \"&a

16条回答
  •  轮回少年
    2020-12-17 09:49

    You could use Array.from to create an array with the final size, and then use the callback argument to actually populate it:

    const intersperse = (arr, sep) => Array.from(
        { length: Math.max(0, arr.length * 2 - 1) }, 
        (_, i) => i % 2 ? sep : arr[i >> 1]
    );
    // Demo:
    let res = intersperse([1, 2, 3], "&");
    console.log(res);

提交回复
热议问题