使用javascript过滤2d数组 [英] filtering 2d arrays using javascript

查看:64
本文介绍了使用javascript过滤2d数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2D数组,需要过滤具有日期字段(3d列)的行

I have a 2D array where I need to filter the rows having date field (3d column)

var data = [
['1','a','12-12-2019','A'],
['2','b','','A'],
['3','c','12-1-2019','A'],
['4','d','','A'],
];

预期结果是

result = [
['1','a','12-12-2019','A'],
['3','c','12-1-2019','A'],
];

为囚犯使用循环非常耗时,是否有最快的检索方法?

Using for loop for comprisons is time intensive, Is there a fastest way to retrieve?

推荐答案

我不会担心使用循环来做到这一点-这就是循环的目的.

I wouldn't worry about using a loop to do that - this is what loops are for.

您可以只使用 Array.prototype.filter()以确保每个数组的第二个位置都有一个值,并返回是否为真.

You could just use Array.prototype.filter() to make sure that there's a value in the 2nd position of each array, returning whether it's truthy or not.

var data = [
  ['1','a','12-12-2019','A'],
  ['2','b','','A'],
  ['3','c','12-1-2019','A'],
  ['4','d','','A'],
];

// Used a classic `function` keyword because you're using this in a Google apps script
const result = data.filter(function(item) {
  return item[2];
});

console.log(result);

这篇关于使用javascript过滤2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆