Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
¿Por qué este bucle for anidado empuja 1 elemento más de lo que debería? El conjunto de datos es 65, pero la matriz tiene una longitud de 68

He estado tratando de averiguar por qué, pero no saber lo suficiente for loop no permite saber por qué sucede esto.

Estoy haciendo lo siguiente:

  1. Obtenga una columna de datos (Categorías) usando getvalues()
  2. Bucle a través de él y aísle cada valor para una mayor comparación
  3. Inserte las otras categorías en una matriz (para ignorarlas al comparar cada una con los datos de la fila en la siguiente iteración;
  4. Compare la primera columna de cada fila de un conjunto de datos con la categoría aislada en el paso 2;

Me está dando las filas correctas donde se encuentra cada categoría en los datos, pero cuando envío ese valor a una matriz, empuja una más de lo que debería, lo que da como resultado una matriz más grande que los valores de la hoja.

 const categories = catSubSheet.getRange(2, 1, catSubSheet.getLastRow(), 3).getValues(); const subCategories1 = categories.filter(e => e[1] != '').map(function (e) { return e[1] }); const sheetData = sheet.getRange(5, 1, sheet.getLastRow(), 15).getValues(); var sub1Array = []; var subCategory1 = ''; for (let n = 0; n < subCategories1.length; n++) { let subs1ToIgnore = []; subCategory1 = subCategories1[n]; //PUSHES SUBCATEGORIES 1 TO IGNORE IN THE FOLLOWING ITERATION for (let a = 0; a < subCategories1.length; a++) { if (subCategories1[a] != subCategory1) { subs1ToIgnore.push(subCategories1[a]) } } let found; for (let n = 0; n < sheetData.length; n++) { const rowData = sheetData[n][0] rowData.toString().trim(); if (rowData !== '' && rowData === subCategory1) { found = true startRowsSub1 = n + 5 } if (found) { sub1Array.push([subCategory1]) } if (subs1ToIgnore.indexOf(rowData) > - 1) { found = false } } }

Los datos comienzan en la fila 5.

Aquí están los registros: ingrese la descripción de la imagen aquí

Agradezco cualquier ayuda.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Asegúrese de aplicar compensaciones al hacer getRange especialmente cuando se trata de datos que no comienzan en la primera fila.

Dado que su guión es bastante torpe, lo he revisado. Vea la respuesta a continuación.

Guion:

 //THIS FUNCTION FORMATS CELL BACKGROUND COLORS AND SPREADS THE FORMULAS FROM ROW 4 (WHICH IS HIDDEN) THROUGH THE SHEET function formatBOQcells() { const SS = SpreadsheetApp.getActiveSpreadsheet(); const sheet = SS.getSheetByName('Test') const catSubSheet = SS.getSheetByName('Categories and Subcategories') const categories = catSubSheet.getRange(2, 1, catSubSheet.getLastRow() - 1, 3).getValues(); const subCategories1 = categories.filter(e => e[1]).map(function (e) { return e[1] }); // get ColA, transform to 1D array and remove blank cells const sheetData = sheet.getRange(5, 1, sheet.getLastRow() - 4, 1).getValues().flat().filter(String); // this will store the current subcategory var currSubCategory = ['']; // for each sheetData row const output = sheetData.map(item => { // check if description a subcategory if(subCategories1.includes(item)) { // if subcategory, save it as current subcategory currSubCategory = [item]; // return its value return currSubCategory; } // if item is this row, write nothing if(item == 'Sub Total for Pipework') { return ['']; } // if item is not a subcategory, assign the current subcategory return currSubCategory; }); sheet.getRange(5, 3, output.length, output[0].length).setValues(output); }

Nota:

  • El tercer parámetro es la longitud de los datos. Y dado que no comienza en 1, debe compensar su parámetro para obtener el número exacto
  • Para obtener el desplazamiento adecuado, debe restar cuántas filas omitió hasta la última fila (suponiendo que todas las filas sean válidas/sin filtrar).
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!