数组索引选择,就像在 numpy 中一样,但在 JavaScript 中



我有一个 3x3 数组:

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

并希望获取它的第一个 2x2 块(或任何其他 2x2 块(:

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

我会写

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

以获得正确的结果。

我尝试过javascript:

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

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

可以使用Array.sliceArray.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);

您可以使用.map().slice()方法:

var my_array = [[0,1,2],
[3,4,5],
[6,7,8]];
var result = my_array.slice(0, 2).map(a => a.slice(0, 2));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

您可以获取索引对象和所需子数组的长度。然后对切片的子数组进行切片和映射。

var array = [[0, 1, 2], [3, 4, 5], [6, 7, 8]],
length = { x: 2, y: 2 },
indices = { i: 0, j: 0 },
result = array.slice(indices.i, indices.i + length.x).map(a => a.slice(indices.j, indices.j + length.y));

console.log(result);

它似乎不是一个 3x# 数组,它只是数组的数组。

您可以首先使用 slice 获取仅包含前两个元素的数组,即

[[0, 1, 2],[3, 4, 5]]

然后使用 Reduce 返回一个新数组,并在其中仅获取前两个值

var my_array = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
];
let x = my_array.slice(0, 2).reduce(function(acc, curr) {
acc.push(curr.slice(0, 2))
return acc;
}, [])
console.log(x)

const input = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
];
let result =[]
input.forEach(([a, b], index) => {if(index < 2) result.push([a, b])})
console.log(result);

如果你打算经常使用矩阵,那么你应该看看math.js。

请尝试以下操作:

var my_array = [[0,1,2],
[3,4,5],
[6,7,8]];
var matrix = math.matrix(my_array);
var subset = matrix.subset(math.index([0, 1], [0, 1]));

工作示例。

相关内容

最新更新