Reputation: 9
I would like to skip an iteration of code if, the data in a cell does not match a string - number - number format. For example, the desired format is Apple-34-56. If the array that I defined has a format such as Apple-Grape-23, or any other variation contrary to the desired format, it should skip to the next iteration.
function populateData (sheet1, sheet2) {
var dataRange = sheet1.getRange("A:A").getValues();
for (var i = 0; dataRange.length; i++) {
if (dataRange !== string-number-number) {
continue;
}
}
}
Is this the proper way to set up the condition?
Upvotes: 0
Views: 76
Reputation: 14820
You can use a lambda to do your array filtering, for example
dataRange.filter(i => i.match(/^\w+-\d+-\d+$/)) // only include matching elements
.forEach(x => {
console.log(x);
// process the array element how you want
});
(using Barmar's regular expression test /^\w+-\d+-\d+$/ — thanks)
Upvotes: 0
Reputation: 3679
What you are asking for is a regular expression to match your desired constraints.
I.e. if you meant "(any-length word)-(any-length number)-(any-length number)" your if statement would become:
if (! dataRange[i].match(/^\w+-\d+-\d+$/)) {...};
// (Notice the `[i]` I guess you missed 😉)
That being said, you can even avoid the continue statement an make which are your targeted inputs even more clear:
const re_fmt = /^\w+-\d+-\d+$/;
function populateData (sheet1, sheet2) {
var dataRange = sheet1.getRange("A:A").getValues();
for (
let i = 0;
i < dataRange.length;
i++
) if (
dataRange[i].match(re_fmt)
) {
/* Your code... */
}
}
Upvotes: 1
Reputation: 562
A quick easy solution:
function populateData(sheet1, sheet2) {
var dataRange = sheet1.getRange("A:A").getValues();
for (var i = 0; i < dataRange.length; i++) {
var cellValue = dataRange[i][0]; // Accessing the value of the cell
// Splitting the cell value into parts using "-"
var parts = cellValue.split("-");
// Checking if the cell value has the desired format: string-number-number
if (parts.length === 3 && !isNaN(parts[1]) && !isNaN(parts[2])) {
// Proceed
} else {
// Skip this iteration if the format doesn't match
continue;
}
}
}
Upvotes: 0