I’m using the below code to check if the input value match with any value of google sheet column.
The logger returns an array of all phone numbers in the specified column, but the for loop works only for the first phone number in the array. And also I would be grateful if you guide how to get the same results using if (allNumbers.flat().indexOf(newPhone) != -1)
and which way is better.
function phoneSearch(newPhone) {
try {
var ss = SpreadsheetApp.openByUrl("URL");
var sheet = ss.getSheetByName("sheet name");
var allNumbers = sheet.getRange(2, 2, sheet.getLastRow() - 1, 1).getDisplayValues();
Logger.log(allNumbers.length);
for (var i = 0; i < allNumbers.length; i++) {
if (allNumbers[i][0] == newPhone) {
var result = "not available"
} else {
var result = "available"
};
return result;
}
} catch (e) {}
}
3
Answers
Understanding the Issue:
The primary problem with your code is the placement of the return statement within the loop. As soon as the first iteration of the loop is executed, the function returns result, preventing the loop from checking the rest of the phone numbers.
Corrected Code:
Explanation of Changes:
Using indexOf:
Explanation:
allNumbers.flat()
converts the 2D array into a 1D array, making it suitable for indexOf.indexOf
returns the index of the element if found, or -1 if not found.indexOf
result.Which Method is Better:
indexOf
might be slightly faster.Ultimately, the best method depends on your specific use case and performance requirements.
Additional Considerations:
getValues()
instead ofgetDisplayValues()
if you’re working with numerical values.By following these guidelines, you should be able to effectively check if a phone number exists in your Google Sheet.
Your function always returns from the first iteration of the loop. You should return only if the number is taken, and if it isn’t, continue checking the other numbers.
Others on this page have explained that your loop returns after one iteration
Array.flat is a useful way to do what you want.
It is as simple as
If you are worried about the execution time, you really should do this