javascript - 在javascript中从多维数组中删除特殊元素

标签 javascript arrays multidimensional-array

我的数组如下所示:

var my_array=[
  [[1,0], [2,2], [4,1]],
  [[4,9], [3,1], [4,2]],
  [[5,6], [1,5], [9,0]]
]

我想过滤上面的 my_array 并删除所有数组(例如 [[4,9], [3,1], [4,2]]) 来自上面的数组 IF 数组的所有 子数组 在 1. 位置 (child array[1])

所以我的结果应该是这样的:

var result_array=[
  [[1,0], [2,0], [4,1]],
  [[5,6], [1,5], [9,0]]
]

See above: Remove second array from my_array because the second child arrays do not include a 0-column at the first index.

我的想法是使用类似这样的代码,但我无法真正让它工作:

var my_array=[
    [[1,0], [2,2], [4,1]],
    [[4,9], [3,1], [4,2]],
    [[5,6], [1,5], [9,0]]
]
  
 result_array = my_array.filter(function(item){ return item[1] != 0 })
console.log(JSON.stringify(result_array))

最佳答案

简单的方法是使用 Array#some在外部数组的 filter 中查找其中符合我们标准的任何数组,并使用 Array#includes (或者在旧版浏览器上使用 Array#indexOf,与 -1 进行比较表示未找到)在 find 回调中查看子数组是否包含 0 .

在 ES2015+ 中

var my_array=[
  [[1,0], [2,2], [4,1]],
  [[4,9], [3,1], [4,2]],
  [[5,6], [1,5], [9,0]]
];
var filtered = my_array.filter(middle => middle.some(inner => inner.includes(0)));
console.log(filtered);
.as-console-wrapper {
  max-height: 100% !important;
}

或者在 ES5 中:

var my_array=[
  [[1,0], [2,2], [4,1]],
  [[4,9], [3,1], [4,2]],
  [[5,6], [1,5], [9,0]]
];
var filtered = my_array.filter(function(middle) {
  return middle.some(function(inner) {
    return inner.indexOf(0) != -1;
  });
});
console.log(filtered);
.as-console-wrapper {
  max-height: 100% !important;
}

关于javascript - 在javascript中从多维数组中删除特殊元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47495321/

相关文章:

javascript - 使用javascript从维基百科html表行中提取数组

javascript - iframe onload 在 url 生成 pdf 输出时不起作用

javascript - 如何进行线性插值?

javascript - 未捕获的 promise Dom 异常

javascript - 在 React Redux 应用程序中使用 JWT 身份验证 token 的正确方法

php - 使用内爆创建新表

javascript - 如何将所有值添加到该数组中?每次创建一个新的 CLIENT 数组并向其推送值

python - 从 Python : passing list of numpy pointers 调用 C

c - 在 C 中初始化多维数组

arrays - 如何在 postgres 的 where 子句中调用声明的数组变量?