How to insert a new element in between all elements of a JS array?

后端 未结 17 1219
清歌不尽
清歌不尽 2020-12-29 20:38

I have an array [a, b, c]. I want to be able to insert a value between each elements of this array like that: [0, a, 0, b, 0, c, 0].

I gues

17条回答
  •  無奈伤痛
    2020-12-29 20:45

    This looks like the intersperse algorithm but does some addition to the head and tail as well. So i call it extrasperse.

    var arr         = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
        extrasperse = (x,a) => a.reduce((p,c,i) => (p[2*i+1] = c, p), Array(2*a.length+1).fill(x));
    
    console.log(JSON.stringify(extrasperse("X",arr)));

提交回复
热议问题