Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

How to filter an array of arrays?

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  

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 

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ECMAScript 6

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

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

ECMAScript 5

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

In the comments, “classic way” refers to the ES5 method.

Explanation

.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.

See also


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...