Check the presence of a specific cell within an array of cells

Currently, I am attempting to navigate through a spreadsheet column while disregarding any duplicate values. My approach involves using TextFinder to gather all cells with matching values and then adding them to an array named "duplicates."

Throughout each iteration, I have an if statement that checks if the current cell is included in the "duplicates" array. If it is, the program should proceed to the next iteration. However, despite my efforts using both "includes()" and "indexOf()", the condition does not seem to work as intended.

Below is the code snippet:

let duplicates = [];
    for (let row = 1; row <= range.getNumRows(); row++) {
      const cell = range.getCell(row, 1);
      const value = cell.getValue();

      if (!duplicates.includes(cell)) {
        let array = range.createTextFinder(value).findAll();
        const cellIndex = array.indexOf(cell);
        array.splice(cellIndex, 1);
        duplicates.push(...array);
      }
    }

I am unsure why this logic is not functioning correctly. As a newcomer to coding, I acknowledge that this may be due to a beginner's error.

Any assistance provided would be greatly appreciated! Thank you!

Answer №1

For those looking to identify the distinct values in a column, consider this approach:

function findUniqueValuesInColumn() {

  return [...new Set(
    SpreadsheetApp.getActiveSpreadsheet()
                  .getSheetByName(`Sheet1`)
                  .getRange(`A:A`)
                  .getValues()
                  .flat()
                  .filter(Boolean)
  )]

  /* Alternatively,

  const uniqueValues = [...new Set(
    SpreadsheetApp.getActiveSpreadsheet()
                  .getSheetByName(`Sheet1`)
                  .getRange(`A:A`)
                  .getValues()
                  .flat()
                  .filter(Boolean)
  )];

  */

}

This function transforms all column values into an array of unique entries, eliminating any empty cells. It achieves this by turning a Set of values into an array.

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

React JavaScript application encountered an error: Uncaught SyntaxError due to an unexpected token '<'

My program encountered a syntax error at line <div>Hello World!</div> This is the code that is causing the error <!DOCTYPE html> <html> <head> <script src="libs/react.min.js"></script> <script src="lib ...

The incorrect ordering of my array within a nested ng-repeat in AngularJS

I have extracted Json data from a mongodb database collection. Successfully displayed the keys of this json. Currently attempting to present an array in a table using a double ng-repeat in my view. Although I am close to achieving my desired outcome, th ...

I am unable to invoke a JavaScript function from PHP code

Please Note: Despite all my efforts, I have been unable to find a solution to this issue. I have scoured numerous online resources, including Stack Overflow, without success. Surprisingly, I could not locate a relevant question on Stack Overflow addressing ...

Is the entire web page generated on the server with each request using getServerSideProps()?

As I understand it, getServerSideProps will dynamically generate the complete page on every request, rather than pre-building it. But does getServerSideProps always generate the entire page upon each server request, or only when the data in the database ha ...

Updating a Parent component from a Child component in React (Functional Components)

My functional component RoomManagement initiates the fetchRooms function on the first render, setting state variables with data from a database. I then pass setLoading and fetchRooms to a child component called RoomManagementModal. The issue arises when t ...

Utilize a locally stored VueJs file rather than importing it from an external source

Starting my journey with VueJs using single file application has been quite interesting. Initially, I had everything in a single html page with both javascript and CSS styles embedded within it. To avoid fetching VueJs features online, I downloaded the V ...

What is the best way to extract the text from a class only when it is nested within a particular header tag?

const request = require ('request'); const cheerio = require('cheerio'); const fs = require ('fs'); request("http://kathmandupost.ekantipur.com/news/2018-08-31/bimstec-summit-multilateral-meet-underway.html", (error, response ...

I am looking to create a PHP script that restricts access to individuals under the age of 18 based on the current

I'm looking for a way to use Php, javascript, or ajax to restrict access for individuals under 18 years old based on the current date. Any suggestions on how I can achieve this? Could someone please review my code for calculating age onblur or onSubm ...

What is the best way to transfer a segment of CSS, HTML, and JavaScript code from one static template to another?

I have a collection of static files (html, css, and js) and I've identified a specific piece of code (let's say a dinosaur animation) that I want to move to another set of static files (a separate project I'm working on with a different temp ...

The function onClick does not function properly when used with the <p> element, but it works flawlessly with the <button> element

export function SignoutButton() { return ( <p onClick={() => signOut({ callbackUrl: "/" })}> <IoIosLogOut /> Logout </p> ); } I was struggling with a function in my next.js project that wasn't wo ...

"The reactivity of VueJs array of objects is not triggering properly when there is a change in

My state includes an array of objects structured like this: data() { return { users: [{id: 1, name: 'bob'}, {id: 2, name: 'bill'}] } } After modifying the data as shown below: this.users[0].name = 'Mary' The watc ...

The AJAX response doesn't seem to be halting

My AJAX request looks like this: $.ajax({ url: "AutoRFQ_Vendors_ST.aspx/BindVesselGrid", type: "POST", timeout: 3000, data: JSON.stringify(sendingdata), ...

Tips for changing the size of a background image using JavaScript on the fly

I am a beginner in the world of programming and currently working on my very first mini-project - a word definition game. One of the challenges I am facing is related to an event listener on an input field, where I aim to change the background image every ...

AngularJS Input field fails to update due to a setTimeout function within the controller

I am currently working on a project that involves AngularJS. I need to show a live clock in a read-only input field, which is two-way bound with data-ng-model. To create this running clock effect, I am using a JavaScript scheduler with setTimeout to trigge ...

Adjust width based on value dynamically

I currently have a div that is sized at 250px, housing 3 child divs within it. My goal is for each of these 3 divs to dynamically scale based on their respective values, eventually reaching 100% width. This is the code snippet I am working with: <di ...

Navigation Bar Revamp

Check out the colorful navigation bar on this page: The navigation bar appears distorted when I zoom in/out. Is there a way to resolve this issue? ...

Using regular expressions to replace a string with the captured text

I am trying to replace all non-alphanumeric characters in a string with themselves enclosed in square brackets "[ ]". This is what I have attempted: var text = "ab!@1b*. ef"; var regex = /\W/g; var result = text.replace(regex, "[$0]"); console.lo ...

What are the potential drawbacks of relying heavily on socket.io for handling most requests versus using it primarily for pushing data to clients?

Is it advisable to switch AJAX routes (called with $.Ajax in jquery) like: GET /animals GET /animals/[id] POST /animals To socket.io events (event bound on client and server for client response): emit("animals:read") emit("animals:read", {id:asdasd}) ...

Guide on how to show an icon in Meteor when a link is clicked

Is there a way to display a viewed icon upon clicking a link in Meteor? On my list of jobs page, when a user clicks on a job, they are taken to the description page. I would like to add an icon to the post indicating that the user has viewed it. ...

Error: Unable to assign value to '18dit075' property as it is not defined in Node.js

var id = req.query.id; var username = req.query.name; var password = req.query.password; console.log(req.query); var data = { people:{ } } data.people[id] = { username: username, password: password, ...