简体   繁体   中英

Assign mutiple ranges (non consecutive) to a single Constants (apps script)

I have this (below) as part of my apps script and I am wondering if there is a way to simplify this:

const fieldRange = ["C9","C10","C11","C12","C15","C16","C17","C18","C19","C20","C21","C22","C23","C24","C25","C26","C27","C28","C29","C30","C33","C34","C35","C36","C37","C38","C41","C42","C45","C46","C47","C48","C49","C50"]

maybe something like ['(C9:C12)','(C15:C30)' , etc.

In your situation, how about the following sample script?

Sample script:

 // This value is from your question. const fieldRange = ["C9", "C10", "C11", "C12", "C15", "C16", "C17", "C18", "C19", "C20", "C21", "C22", "C23", "C24", "C25", "C26", "C27", "C28", "C29", "C30", "C33", "C34", "C35", "C36", "C37", "C38", "C41", "C42", "C45", "C46", "C47", "C48", "C49", "C50"]; // Ref: https://tanaikech.github.io/2021/10/08/compiling-continuous-numbers-using-google-apps-script/ const compilingNumbers = (ar) => { const { values } = [...new Set(ar.sort((a, b) => a - b))].reduce((o, e, i, a) => { if (o.temp.length == 0 || (o.temp.length > 0 && e == o.temp[o.temp.length - 1] + 1)) { o.temp.push(e); } else { if (o.temp.length > 0) { o.values.push({ start: o.temp[0], end: o.temp[o.temp.length - 1] }); } o.temp = [e]; } if (i == a.length - 1) { o.values.push(o.temp.length > 1? { start: o.temp[0], end: o.temp[o.temp.length - 1] }: { start: e, end: e }); } return o; }, { temp: [], values: [] }); return values; }; const r1 = fieldRange.reduce((o, e) => { const k = e.replace(/[0-9]+/, ""); const v = Number(e.toUpperCase().replace(/[AZ]+/, "")); o[k] = o[k]? [...o[k], v]: [v]; return o; }, {}); const res = Object.entries(r1).flatMap(([k, v]) => compilingNumbers(v).map(({ start, end }) => `${k}${start}:${k}${end}`)); console.log(res); // ["C9:C12","C15:C30","C33:C38","C41:C42","C45:C50"]

  • When this script is run, ["C9:C12","C15:C30","C33:C38","C41:C42","C45:C50"] is obtained.

  • If you want to retrieve the value like maybe something like ['(C9:C12)','(C15:C30)', etc. , please modify ${k}${start}:${k}${end} to (${k}${start}:${k}${end}) .

Note:

  • From your showing sample value, this script supposes that all values in your expected array including A1Notation are only one cell. Please be careful about this.

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM