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

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

    You could use .reduce():

    function intersperse(arr, val) {
      return arr.reduce((acc, next) => {
        acc.push(next);
        acc.push(val);
        return acc;
      }, [val]);
    }
    
    console.log(intersperse(['a', 'b', 'c'], 0));

    Or to accomplish this by modifying the original array:

    function intersperse(arr, val) {
      for (let i = 0; i <= arr.length; i += 2) {
        arr.splice(i, 0, val);
      }
    
      return arr;
    }
    
    console.log(intersperse(['a', 'b', 'c'], 0));

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

    It could be done with strings by splitting and joining.

    var arr = ['a', 'b', 'c'];
    var newArray = ("0," + arr.toString().split(",").join(",0,")).split(",");
    console.log(newArray);

    0 讨论(0)
  • 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)));

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

    Another way is to use some functional methods like zip and flat. Check out lodash.

    const array = ['a', 'b', 'c']
    const zeros = Array(array.length + 1).fill(0)
    const result = _.zip(zeros, array).flat().filter(x => x !== undefined)
    console.log(result)
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

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

    function insert(arr, elm) {
      var newArr = [];
      for(var i = 0; i < arr.length; i++) {   // for each element in the array arr
        newArr.push(elm);                     // add the new element to newArr
        newArr.push(arr[i]);                  // add the current element from arr
      }
      newArr.push(elm);                       // finally add the new element to the end of newArr
      return newArr;
    }
    
    console.log(insert(["a", "b", "c"], 0));

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

    For getting a new array, you could concat the part an add a zero element for each element.

    var array = ['a', 'b', 'c'],
        result = array.reduce((r, a) => r.concat(a, 0), [0]);
        
    console.log(result);

    Using the same array

    var array = ['a', 'b', 'c'],
        i = 0;
    
    while (i <= array.length) {
        array.splice(i, 0, 0);
        i += 2;
    }
    
    console.log(array);

    A bit shorter with iterating from the end.

    var array = ['a', 'b', 'c'],
        i = array.length;
    
    do {
        array.splice(i, 0, 0);
    } while (i--)
    
    console.log(array);

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