if-statementgoogle-apps-scriptgoogle-sheetsdata-extraction

Google Script Run Function IF text in another sheet's column contains a 'specific text'


I've done extensive search for this, but none of them seems to work. They all just give me a blank sheet. Sample sheet

Basically I have a function that extracts data from Col. B in DATA, to Result. Then does some other things, split, trim etc...

I want to run this function when the text in Col. A in DATA is 250P.

enter image description here

So it would be like: IF (DATA!A1:A contains text "250p" then run function EXTRACT).

This is the code I have as of now:

//this extract works fine but I just need this to work for only those with value 250 in Col A//

function EXTRACT() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A1').setFormula('=EXTRACTDATA(DATA!A1:A)');

}

function IF250() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('DATA');
  var range = sheet.getRange('DATA!A1:A');
  var values = range.getValues();

  if (values[i] == "250g") {
    EXTRACT();

Better yet, If I can have the data set in 2 separate sheets. The 250s in one sheet & 500s in one sheet. But this is not necessary.


Solution

  • After reviewing your sheet, this is a possible solution

    Code.gs
    const sS = SpreadsheetApp.getActiveSpreadsheet()
    function grabData() {
      const sheetIn = sS.getSheetByName('data')
      const sheetOut = sS.getSheetByName('Desired Outcome')
      const range = 'A2:B'
      /* Grab all the data from columns A and B and filter it */
      const values = sheetIn.getRange(range).getValues().filter(n => n[0])
      /* Retrieve only the names if it containes 250p */
      /* In format [[a], [b], ...] */
      const parsedValues = values.map((arr) => {
        const [type, name] = arr
        if (type.toLowerCase().includes('250p')) {
          return name.split('\n')
        }
      })
        .filter(n => n)
        .flat()
        .map(n => [n])
      /* Add the values to the Desired Outcome Sheet */
      sheetOut
        .getRange(sheetOut.getLastRow() + 1, 1, parsedValues.length)
        .setValues(parsedValues)
    }