Search code examples
javascriptjsonapigoogle-apps-scriptgoogle-sheets

How to filter filter data after extracted data in Json form


I've extracted data but having problem to filter some data that I would like to get only. Below is the code:

// 7. for each itemid, extract the metrics required (the list of metrics in section 2) //
      outdata.forEach(function (outJson) {
        var temp = []
        for (var j = 0; j < head.length; j++) {
          
          temp.push((outJson[head[j]]) ? outJson[head[j]] : "" ) // ? : works like an if statement (condition ? value if true : value if false) //

        }
        if(temp.length>=34){
            temp.pop() // remove the last empty column 
        }
 
        temp.push(counter)
        // console.log(temp)
        toPrint.push(temp)
        counter++
      })
    }

The condition that I want to filter is as below but not sure how to amend and incorporate into the above chunk to make it work:

temp= temp.filter(function (row) { return (row[24] ==1); })

Solution

  • I'm not sure to understand everything well. As far as I understand, you can simply replace

    temp = temp.filter(function (row) { return (row[24] ==1); })
    

    by

    if(row[24] == 1) {
        // do stuff
    }
    

    And, if your aim is to, for each outdata, get the item n°24 and if, and only if, it's 1, you can simplify your code as:

    // Map return an array of every 24th values
    // Filter return an array of only one
    outdata.map((data) => data[head[24]]).filter((data) => data == 1)
    
    // To get the number of one, you can then simply use
    outdata.length