如何过滤一个数组的数组? [英] How to filter an array of arrays?

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

问题描述

我有这个二维数据数组(我们将其称为变量arr),它表示具有多个字段的表:

I've this 2D array of data (let's call the variable arr) that represents a table with various fields:

     [1]   [2]   [3]   [4]   
[1],Fruit,Apple,Red,10  
[2],Fruit,Apple,Green,20  
[3],Berry,Strawberries,Red,5  
[4],Tuber,Potato,Yellow,2  

在这种情况下,我需要按第3列= Red(我不想在所有表中仅在第3列中搜索Red)过滤arr变量,以获得以下信息:

In this case I need to filter the arr variable by column 3 = Red (I don't want to search Red in all the table, just in column 3) obtaining this:

    [1]   [2]   [3]   [4]   
[1],Fruit,Apple,Red,10  
[2],Berry,Strawberries,Red,5 

如何将.filter函数应用于2D数组以对单个字段/列进行过滤?

How is it possible to apply the .filter function to a 2D array in order to filter for a single field/column?

推荐答案

ECMAScript 6

let filtered = arr.filter(dataRow => dataRow[2] === 'Red');

@ozeebee指出,Google App脚本当前不支持ES6,因此您应尝试以下操作:

As noted by @ozeebee, ES6 is currently not supported in Google App Scripts, so you should try the following:

var filtered = arr.filter(function (dataRow) {
  return dataRow[2] === 'Red';
});

在注释中,经典方式"是指ES5方法.

In the comments, "classic way" refers to the ES5 method.

.filter函数采用单个参数,该参数是该函数的回调,如果应保留数组条目,则返回true;如果应删除它,则返回false,即过滤.在这种情况下,我们应该检查表行的第三列是否等于Red.代码:return dataRow[2] === 'Red'等于:

.filter function takes a single parameter which is a callback to a function that returns true if array entry should remain or false if it should be removed, that’s the filtering. In this case, we should check whether third column of table row equals to Red. The code: return dataRow[2] === 'Red' is equal to:

if (dataRow[2] === 'Red') {
  return true;
} else {
  return false;
}

因为比较的结果是一个布尔值.

Because the result of comparison is a boolean.

这篇关于如何过滤一个数组的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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