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

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

问题描述

我有这个 2D 数据数组(我们称之为变量 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 过滤 arr 变量(我不想在所有表中搜索红色,只在第 3 列中)获得:

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 函数应用于二维数组以过滤单个字段/列?

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 Scripts 目前不支持 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 函数采用单个参数,该参数是对函数的回调,如果数组条目应保留,则返回 truefalse应该删除,这就是过滤.在这种情况下,我们应该检查表格行的第三列是否等于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天全站免登陆