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

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

    If you want to insert elements only after existing ones:

    console.log(["a", "b", "c"].map(i => [i, 0]).flat())

    0 讨论(0)
  • 2020-12-29 21:01

    You just need to loop over the array elements and add the new element in each iteration, and if you reach the last iteration add the new element after the last item.

    This is how should be your code:

    var arr = ['a', 'b', 'c'];
    var results = [];
    arr.forEach(function(el, index) {
      results.push(addition);
      results.push(el);
      if (index === arr.length - 1)
            results.push(addition);
    });
    

    Demo:

    This is a Demo snippet:

    var arr = ['a', 'b', 'c'];
    var results = [];
    var addition = 0;
    arr.forEach(function(el, index) {
      results.push(addition);
      results.push(el);
      if(index === arr.length -1)
            results.push(addition);
    });
    console.log(results);

    0 讨论(0)
  • 2020-12-29 21:03

    all of the above methods in very long strings made my android computer run on React Native go out of memory. I got it to work with this

    let arr = ['a', 'b', 'c'];
    let tmpArr = [];
    
    for (const item in arr) {
      tmpArr.push(item);
      tmpArr.push(0);
    }
    
    console.log(tmpArr);

    0 讨论(0)
  • 2020-12-29 21:05

    Straight forward way of inserting only between:

    const arr = ['a', 'b', 'c'];
    
    arr.map((v, i) => !i || i === arr.length - 1 ? [v] : [0, v]).flat() 
    
    0 讨论(0)
  • 2020-12-29 21:10

    You could do

    let arr = ['a', 'b', 'c'];
    
    arr = arr.reduce((a, b) => {
        a.push(0);
        a.push(b);
        return a;
    }, []);
    arr.push(0);
    console.log(arr);

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