首页 > 解决方案 > 数组索引选择,如 numpy 但在 javascript 中

问题描述

我有一个 3x3 数组:

var my_array = [[0,1,2],
                [3,4,5],
                [6,7,8]];

并想要获得它的第一个 2x2 块(或任何其他 2x2 块):

[[0,1], 
 [3,4]]

用 numpy 我会写:

my_array = np.arange(9).reshape((3,3))
my_array[:2, :2]

得到正确的结果。

我在javascript中试过:

my_array.slice(0, 2).slice(0, 2);

但第二个切片影响第一个维度,什么都不做。我注定要使用 for 循环,还是有一些新的 ES6 语法可以让我的生活更简单?

标签: javascriptarraysnumpymultidimensional-arrayindexing

解决方案


可以使用Array.slice和的组合Array.map

const input = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8]
];

const result = input.slice(0, 2).map(arr => arr.slice(0, 2));

console.log(result);


推荐阅读