代码之家  ›  专栏  ›  技术社区  ›  Hugo

使用数组的数组:如何使用javascript将所有元素按一个向前推

  •  2
  • Hugo  · 技术社区  · 8 年前

    这是我的数组:

    arr_1 = [1,2,3]
    arr_2 = [4,5,6]
    arr_3 = [7,8,9]
    
    arr = [arr_1, arr_2, arr_3]
    arr = [[1,2,3], [4,5,6], [7,8,9]]
    

    我要做的是按如下方式推送所有元素,以便最终数组如下所示,并在数组的开头插入另一个元素:

    arr = [[i,1,2], [3,4,5], [6,7,8], [9]]
    

    所有子数组不得超过3个元素。

    谢谢你的帮助。

    7 回复  |  直到 8 年前
        1
  •  4
  •   Nina Scholz    8 年前

    您可以访问所有内部数组并取消移动上一个循环中的剩余值。

    var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
        chunk = 3,
        item = 'x',
        i = 0,
        temp = [item];
        
    while (i < array.length) {
        array[i].unshift(...temp);
        temp = array[i].splice(chunk, array[i].length - chunk);
        i++;
    }
    if (temp.length) {
        array.push(temp);
    }
    
    console.log(array.map(a => a.join(' ')));
        2
  •  2
  •   Ele    8 年前

    您可以使用该功能 reduce

    var arr = [[1,2,3], [4,5,6], [7,8,9]],
        newElem = "newOne",
        all = [newElem, ...arr.reduce((a, c) => [...a, ...c], [])], // All together
        // Build the desired output asking for the result of:
        // element mod 3 === 0
        result = all.reduce((a, c, i) => { 
          if (i % 3 === 0) a.push([c]);
          else a[a.length - 1].push(c);
          
          return a;
        }, []);
        
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
        3
  •  2
  •   Nenad Vracar    8 年前

    您可以在每次迭代中将上一个数组中的最后一个元素移动到下一个数组中,如果最后一个子数组中有3个以上的元素,则删除最后一个元素并将其添加到新数组中。

    let arr_1 = [1, 2, 3],
      arr_2 = [4, 5, 6],
      arr_3 = [7, 8, 9],
      arr = [arr_1, arr_2, arr_3]
    
    setInterval(function() {
      const last = arr.length - 1;
      const newElement = parseInt(Math.random() * 30)
    
      arr.forEach((a, i) => {
        if(i == 0) a.unshift(newElement);
        if(arr[i + 1]) arr[i + 1].unshift(a.pop())
        else if(arr[last].length > 3) arr[last + 1] = [arr[last].pop()]
      })
    
      console.log(JSON.stringify(arr))
    }, 1000)
        4
  •  1
  •   Mark    8 年前

    您可以通过一个简单的展开(unravel/ravel)非常简洁地做到这一点。调整组大小也很容易。

    let arr = [ [1,2,3], [4,5,6], [7,8,9]]
    let newEl = 0
    let groupSize = 3
    
    var newArr = [];
    var unravelled = arr.reduce((a, c) => a.concat(c), [newEl])
    while(unravelled.length) newArr.push(unravelled.splice(0,groupSize));
    
    console.log(newArr)
        5
  •  0
  •   brk    8 年前

    arr_1 = [1, 2, 3]
    arr_2 = [4, 5, 6]
    arr_3 = [7, 8, 9]
    arr = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]
    ]
    
    function reassignChunk(x) {
      // create an array which will be used to store unwrapped values 
      var newArray = [];
      arr.forEach(function(elem) {
        newArray.push(...elem); //using spread operator to unwrap values
      });
      newArray.unshift(x, limit)
      var modArray = [];
      var m, j, temparray, chunk = 3;
      for (m = 0; m < newArray.length; m = m + limit) {
        // creatinging new array using slice
        modArray.push(newArray.slice(m, m + limit));
      }
      console.log(modArray)
    }
    
    reassignChunk(13, 3)
    arr = [[i,1,2], [3,4,5], [6,7,8], [9]]
        6
  •  0
  •   Paul    8 年前

    假设所有元素都是数字,可以这样做:

    1. 预编 i 到阵列
    2. 展平阵列
    3. 将数组转换为逗号分隔的字符串
    4. 将字符串拆分为最多3个数字子字符串(2个逗号)的块
    5. 将数据块转换回数字数组

    const arr_1 = [1,2,3];
    const arr_2 = [4,5,6];
    const arr_3 = [7,8,9];
    
    const i = 42;
    
    const result = [i,...arr_1,...arr_2,...arr_3].join()
      .match(/(?:[^,]+(,|$)){1,2}[^,]*/g).map( x => x.split(',').map(Number) )
    ;
    
    console.log( result );
        7
  •  0
  •   Redu    8 年前

    您可以按以下方式简单地执行2d取消移动;

    var arr_1 = [1,2,3],
        arr_2 = [4,5,6],
        arr_3 = [7,8,9],
        arr   = [arr_1, arr_2, arr_3],
        us2d  = (a2d,...is) => is.concat(...a2d)
                                 .reduce((r,e,i) => (i%3 ? r[r.length-1].push(e)
                                                         : r.push([e]), r), []);
    console.log(JSON.stringify(us2d(arr,0)));
    console.log(JSON.stringify(us2d(arr,-2,-1,0)));