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

后端 未结 17 1154
清歌不尽
清歌不尽 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:53

    Another way:

    var a = ['a', 'b', 'c'],
      b;
    
    b = a.reduce((arr, b) => [...arr, b, 0], []);
    
    console.log(b);

    0 讨论(0)
  • 2020-12-29 20:53

    let arr = ['a', 'b', 'c'];
    
    function insert(items, separator) {
      const result = items.reduce(
        (res, el) => [...res, el, separator], [separator]);
      return result;
    }
    
    console.log(insert(arr, '0'));

    0 讨论(0)
  • 2020-12-29 20:55

    Another ES6+ version using flatmap (if creation of a new array instead is ok):

    ['a', 'b', 'c', 'd']
        .flatMap((e, index) => index ? [e, 0] : [0, e, 0])
    
    0 讨论(0)
  • 2020-12-29 20:58

    Another way if you want to exclude the start and end of array is :

    var arr = ['a', 'b', 'c']
    var newArr = [...arr].map((e, i) => i < arr.length - 1 ? [e, 0] : [e]).reduce((a, b) => a.concat(b))
    
    console.log(newArr)

    0 讨论(0)
  • 2020-12-29 20:58

    You can use map() with ES6 spread syntax and concat()

    var arr = ['a', 'b', 'c']
    var newArr = [0].concat(...arr.map(e => [e, 0]))
    
    console.log(newArr)

    0 讨论(0)
  • 2020-12-29 20:58

    You can try with the below code. It will add 0 in middle of each two element of the array

    console.log(['a', 'b', 'c'].reduce((r, a) => r.concat(a,0), [0]).slice(1, -1))

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