How to filter an array of arrays?

前端 未结 1 2005
醉梦人生
醉梦人生 2020-12-06 22:31

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,         


        
相关标签:
1条回答
  • 2020-12-06 23:02

    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

    • Array.prototype.filter at Mozilla Developer Network
    0 讨论(0)
提交回复
热议问题