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

使用javascript或lodash创建多维数组

  •  0
  • danday74  · 技术社区  · 6 年前

    我想使用Lodash或Vanilla JS创建这样的多维数组:

    [
      [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
      etc
    ]
    

    这是一个简单的例子,因为我希望这个模式持续到1000000,但是对于演示1到20是可以的。

    有什么想法吗?我试过了 _.range(20) 到目前为止,我需要这个数组是多维的。谢谢

    4 回复  |  直到 6 年前
        1
  •  3
  •   slider    6 年前

    你可以用木屑 chunk :

    const result = _.chunk(_.range(1, 21), 10);
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
        2
  •  5
  •   charlietfl    6 年前

    使用嵌套本机 Array#from()

    const 
       limit = 100,
       fr = Array.from;
    
    const res = fr({ length:limit/10 }, (_,i) => fr({ length:10 }, (_,j) => i*10 + j+1 ));
    
    console.log(res)
        3
  •  3
  •   Conner devopensource    6 年前

    使用普通的javascript:

    x = []
    for (i=1; i<=20; i=i+10) {
        y = []
        for (j=0; j<10; j++) {
            y.push(i + j)
        }
        x.push(y)
    }
    console.log(x)

    对于任何有兴趣的人,我会计时这些答案,这是最快的。使用100万个条目,这个时钟为0.100秒。洛达什区块的时钟在0.110秒后关闭。 Array.from 落后于0.254秒。

        4
  •  3
  •   Akrion    6 年前

    看着 ES6 Array.from 您可以看到的文档 测距仪功能 :

    const range = (start, stop, step) => Array.from({ length: (stop -
    start) / step }, (_, i) => start + (i * step));
    

    因此,考虑到这一点,您可以通过以下方式生成范围:

    range(1, 21, 1)  // account for the 0 with the 21 otherwise you get 1-19
    

    那么所缺少的就是 chunk 功能:

    const range = (start, stop, step) => Array.from({ length: (stop - start) / step }, (_, i) => start + (i * step));
    const chunkBy = (arr, by=2) => arr.reduce((r,c,i) => (i%by==0 ? r.push([c]) : r[r.length-1] = [...r[r.length-1], c], r), [])
    
    console.log(chunkBy(range(1,21,1), 10))

    这个 chunkBy 使用 Array.reduce % 运算符到 数据。