Leveraging the search feature within Google scripts to manipulate arrays

I'm facing a challenge in developing a function to search for regex in a cell and return a specific value if the result is found. The function works fine on an individual cell, but I can't seem to get it to work when applying it as an array to cells B1:B10 instead of just B10. My goal is to optimize the function by making it work as an array for faster performance. Whenever I try to apply the pagetype function to an array, I encounter this error message: TypeError: Cannot find function search in object yfhhh. (line 13). I realize that I need to adjust the function to make it compatible with a range of cells but I'm not sure how to do it. Here's my current code:

function pageType(string) {
  if (string.map)          // Checking if input is an array.
    return string.map(page); // Applying recursively over the array.
   else {
    return page(string);
  }
}

function page(url) {
var productpage = /.*\.html.*/
var homepage = /^http:\/\/www\.domain.com\/$/
var categorypage = /^http:\/\/www\.domain\.com\/.*/
  if (url.search(categorypage) > -1)
    return "Category Page";
  if (url.search(productpage) > -1)
    return "Product Page";
  if (url.search(homepage) > -1)
    return "Homepage";
      else
    return "Brand Page";
        }

Answer №1

An array does not have a search() method. Arrays are a type of object, and within the category of objects, there is also the JSON object.

Objects can include:

  • JSON object {'key':'value'}
  • Array ['element1','element2']

An array is a subset of an object, although it may be confusing to refer to an array as an object. However, this is how the error message interprets it.

When using RegEx, you cannot utilize the indexOf() method, which is applicable to both strings and arrays.

If necessary, you could convert the array into a string:

var myArray = myArray.toString();

Then, you can search for the desired match within the string. If your goal is simply to return a predefined value upon finding a match, converting the array to a string should suffice without needing further extraction of data from the array, which would involve additional processing.

if (typeof url === 'object') {//If data is an array
  url = url.toString();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for resolving the setAttribute() function error message: "Argument of type 'boolean' is not assignable to parameter of type 'string'"

I am currently working on a function that dynamically updates the HTML aria-expanded attribute based on whether it is true or false. However, when I declare element as HTMLElement, I encounter an error stating Argument of type 'boolean' is not as ...

Exploring a collection of objects housed in a json document

Currently, I'm looking to retrieve a collection of objects using JavaScript from a JSON file that resides on my website. While I could easily embed the array of objects directly into my JavaScript code, I am interested in understanding how to work wit ...

Removing the rubber band scrolling feature on Mac computers

While I am pleased with the overall look of my website, I have noticed that users with trackpads on Macs experience distortion when accessing it. I am seeking assistance in addressing this issue, particularly in disabling or minimizing the impact of trackp ...

Endless scrolling feature malfunctioning

On my profile_page.php, the default setting is to display 10 posts (10 rows from the database) for the user. If a user has more than 10 posts, and scrolls to the bottom of the page, the div should expand to reveal the remaining posts (maximum of 10). For e ...

Showing information from asynchronous AsyncStorage.getItems in React Native

In my app, users have to validate their success on challenges by clicking a validation button which saves the "key":"value" pair of the challenge using this function: async function validate(challenge_nb) { try { await AsyncStorage.setItem(challenge_n ...

Webpack is notorious for creating multiple copies of images

Having an issue with Webpack where it's generating duplicate images, one of which is broken. I have an original image image, and after running Webpack, two duplicates are created. One works fine: image, but the other one is broken: image. I'm us ...

Combining react-md with material-ui components: A step-by-step guide

Is it possible to combine react-md and material-ui components together? I am attempting to utilize components from both libraries, however they seem to conflict with each other's styles. Do you have any suggestions or solutions? ...

Displaying the complete response on Angular is possible, but JSON only shows the full response

I'm currently working on a project, and my main concern is: how do I access the response from the first array when all arrays have identical attribute names like body? similar to this: console.log and screen Everything works fine on a simple JSON ser ...

Utilizing the module pattern for efficient event handler implementation

My concern revolves around optimizing the utilization of JavaScript Module Patterns. Here is a basic module snippet from my code that I aim to break down into modules. Each module would consist of a few hundred lines of code. Inquiry : Among methods 1, 2, ...

Returning an array-filled marshaling structure

The structure in the C++ code is defined as follows: typedef struct _a astruct; struct _a { BYTE fi, Sec, *D, *IIV, PV; bool Visited; }; There is also a function that utilizes this structure: astruct DoPDC(string *InitialData); To use this func ...

I encountered an issue while trying to send data from a React.js application to PHP using Axios. However,

I am utilizing react.js, axios, and PHP to transmit data to a MySQL database Below is my react.js code snippet sendData(){ var data = new FormData(); data.append('name', 'jessie'); data.append('time', '12:00'); dat ...

Using JavaScript to invoke a child method within a parent class

Is it recommended to call a child method from a parent class in JavaScript? In the given example in BaseComponent.js, calling this.constructHtml() is returning undefined. What could be causing this issue? Thank you! script.js import Header from './co ...

Is there an equivalent of gsub in JavaScript?

Is there a way to achieve functionality similar to Ruby's gsub in JavaScript? I am working with a local HTML file and need to replace specific template variables with content, but I am struggling to find a solution. The HTML code includes elements lik ...

Reset input value when adding or removing inputs dynamically

Currently, I have an input element that has the capability to clear its value when a button is clicked. Additionally, this input can dynamically add or remove input elements. However, I am facing an issue where after adding an input element, the clear butt ...

Alter numerous classifications based on varying circumstances at regular intervals

This code snippet is designed to change randomly all the <div class="percentx"> elements, for example from <div class="percent31"> to <div class="percent52"> (with values between 1-100). It works smoothly. I ...

How can I enlarge the arrow of the React Tooltip component?

I've extensively reviewed the official documentation, but I couldn't find a way to adjust the size of the arrow in the React tooltip. <span className="icon margin-10-right txtSize20 txtBlue icon_profile-menu icon-tool" data-tip={`&l ...

AngularJS special feature: enhance controllers and views by adding notification capabilities

What is the most efficient method for integrating common notification features into necessary controllers in AngularJS? The objective is to establish local notifications that can be effortlessly included or removed from any controller. Key factors includ ...

Guide on attaching a function to an Element that is dynamically loaded using Ajax

Including multiple Divs with the CSS class "hello" on my page. I then utilize Ajax to retrieve additional Divs also with the CSS class "hello". This leads to a code snippet being triggered upon clicking the Divs: $('.hello').click(function(){ ...

A simple way to initiate an AJAX call once the page has completed loading is by using the `window.location.href` as the

I encountered an issue with my event listener setup function navBtn() { $('#navBtn').on('click', (event) => { window.location.href = 'someotherfile.html'; myAJAXrequest(); }) } The problem I'm facing is that ...

Jade Compilation with Gulp

Currently utilizing gulp-jade, I have encountered an error with a particular template: 557| 558| > 559| 560| .tabs-wrap(ng-show="eventExists"): .contain-center 561| 562| #room-tabs-contain.contain-disable.contain: .contain-center unexpec ...