Avoiding empty spaces within a JavaScript array

I'm currently using a loop array function to automatically populate values, but I've encountered an issue where the array assigns an "undefined" label to blank values. Is there a way to modify this function to skip over any empty cells in my file?

function SubGroup_Update() {

  var Metrics = SpreadsheetApp.openById("10Wl1B4AtdLHJXBbLbMQbSdtRyAb61biCWYpOQEEywIY"); // METRICS spreadsheet
  var Data = SpreadsheetApp.getActiveSpreadsheet(); // DATA spreadsheet
  var SubsMetricSheet = Metrics.getSheetByName('Sub Group Metrics'); // METRICS "Sub Group" sheet 
  var SubGroupDataSheet = Data.getSheetByName("The Sub Group_Numbers") // DATA "Sub Group" sheet
  var SubGroupAllValues = SubGroupDataSheet.getRange(2, 1, SubGroupDataSheet.getLastRow() - 1, SubGroupDataSheet.getLastColumn()).getValues();
  var SubsDataLastRow = SubGroupDataSheet.getLastRow(); // Get the number for the amount of rows with info in the DATA "Sub Group" Sheet
  var FeedDataSheet = Data.getSheetByName("The Feed_Raw") // DATA "Feed" sheet
  var FeedAllValues = FeedDataSheet.getRange(2, 1, FeedDataSheet.getLastRow() - 1, FeedDataSheet.getLastColumn()).getValues();
  //var SubsDataRange = SubGroupDataSheet.getRange("A2:K");  // The entire range of cells in the DATA "Sub Group" Sheet, for sorting
  var SubGroupObj = {}; // Object for "Subgroup" values

  for (var SG = SubGroupAllValues.length - 1; SG >= 0; SG--) // for each row in the "Sub Group" sheet...
  {
    //... Add "Sub Group KEY (Col. #11 [K])" & "FYI Category Name (Col. #1 [A])" in Feed 2D Array.
    SubGroupObj[SubGroupAllValues[SG][10]] = SubGroupAllValues[SG][0];
  }


  for (var F = FeedAllValues.length - 1; F >= 0; F--) // for each row in the "Feed" sheet...
  {
    var Feed_SubGroupKey = FeedAllValues[F][92]; // ...Add "Sub Group (Col. #93 [CO])" in array. 
    {
      // If Sub Group array dont match "Sub Group Key (Col. #93 [CO])" & "FYI Topic Name (Col. #4 [D])... "
      if (SubGroupObj[Feed_SubGroupKey] != FeedAllValues[F][3]) {
        FeedAllValues[F][3] = SubGroupObj[Feed_SubGroupKey]; // ...Change FYI Category Name in FYI Topic Sheet 
      }
    }
  }

  // Decalare var. from 2nd row to last row of FYI Topic sheet
  var FeedDestinationRange = FeedDataSheet.getRange(2, 1, FeedAllValues.length, FeedAllValues[0].length);

  FeedDestinationRange.setValues(FeedAllValues); // placed changed FYI Category 2D array in Mod sheet

  var SubGroupAllRange = SubGroupDataSheet.getRange(2, 1, SubGroupDataSheet.getLastRow() - 1, SubGroupDataSheet.getLastColumn()); // complete range of Mod Status sheet 

  // Sort Sheet by - Category Name, then Category Topic
  SubGroupAllRange.sort([{
    column: 1,
    ascending: true
  }, {
    column: 2,
    ascending: true
  }]);

  Logger.log("The Sub Group Data Sheet has updated  " + SubsDataLastRow - 1 + " data files")

}

Is there anyone who can assist me in adjusting this function to ignore any empty cells it encounters in the file?

Answer №1

It seems you have not specified the array you wish to filter, but there are two possible options available.

You can verify it within your loop

for(var F = FeedAllValues.length-1;F>=0;F--) {
    if (typeof FeedAllValues[F] !== 'undefined') {
}

or you can filter the array before running the loop

FeedAllValues = FeedAllValues.filter(value => typeof value !== 'undefined')

Additionally, it is recommended to define FeedAllValues.length outside of the loop and use a variable for efficiency reasons, as calling FeedAllValues.length every iteration may impact performance.

Answer №2

To check for both empty cells and non-matching cells simultaneously, you can use the following approach:

for(var F = FeedAllValues.length-1;F>=0;F--) // loop through each row in the "Feed" sheet...
  {  
    var Feed_SubGroupKey = FeedAllValues[F][92]; // store value of "Sub Group (Col. #93 [CO])" in an array
    {
      // If Sub Group array does not match "Sub Group Key (Col. #93 [CO])" & "FYI Topic Name (Col. #4 [D])... "
      if ( (SubGroupObj[Feed_SubGroupKey] != FeedAllValues[F][3]) && ("" != FeedAllValues[F][3]) ) 
      { 
        FeedAllValues[F][3] = SubGroupObj[Feed_SubGroupKey]; // update FYI Category Name in FYI Topic Sheet 
      }

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

Suddenly, the Bootstrap CSS appears to have ceased functioning

Here are some of the questions I've already checked out: Bootstrap JavaScript not functioning Twitter Bootstrap dropdown suddenly not operational Comprehensive list of possible issues causing a CSS file to fail All of a sudden, my Bootstrap sty ...

Storing array data locally within an AngularJS application for seamless sharing between two separate applications

I need assistance with persisting and sharing array data var queries = []; between two separate AngularJS applications. One application is for the front end, while the other is for the admin side. Both applications cause the entire page to load when access ...

The title of the homepage is showing up behind the AppBar. Any suggestions on how to correct this?

I encountered an issue with my appBar where the homepage was appearing behind it instead of below it. Here is a snapshot of the problem: https://i.stack.imgur.com/27LjB.png Below are the codes for the AppBar: const Header = () => { const [value, setV ...

Ensuring Jquery validation is triggered before submitting a form to PHP

I have been struggling with a particular issue and decided to seek help. I have a form filled with user data that I have successfully validated using js/jQuery before sending it to php for processing. Here is how I am achieving this: form.submit(functio ...

What is the best way to restrict the input year on @mui/x-date-pickers to a certain range?

Is there a way to restrict the input year range when using @mui/x-date-pickers? I want to limit it from 1000 to 2023 instead of being able to enter years like 0000 or 9999. https://i.stack.imgur.com/0p6j3.jpg I have tried adding a mask to InputProps in my ...

Discover the joy of reading with wrap/unwrap to consume more content in less

I am experimenting with a 'read-more read-less' feature using a wrap method that currently only works for the 'show more' functionality. So, to clarify, if the text exceeds a certain length, I truncate it and insert a read-more-link ( ...

Dispatch an Ajax message with a specified delay in milliseconds before executing the next action

Hey there, I've been attempting to incorporate a delay() or setTimeOut function into this simple send message script, but I seem to be struggling with the syntax. Whenever I try to add these functions, I encounter numerous syntax errors. Even after fi ...

Show the button only if the checkbox is selected

Can someone help me figure out how to show a button on the header bar once the checkbox is selected in a listview? Any assistance would be greatly appreciated. I have tried implementing this on my Codepen: `http://codepen.io/Hin/pen/KpGJZX` ...

I wonder, who is the one executing the function?

In my application, I have encountered an unusual issue. Within my controller, I have two functions - one to add a tab, and one to remove a tab. Below is the code snippet: $scope.createTab = function(){ $scope.addTab("New Tab",50,0); co ...

Is it necessary to append the path with __dirname when utilizing Node's fs.readFile()?

Illustration: fs.readFile(path.join(__dirname, 'path/to/file'), callback); compared to fs.readFile('path/to/file', callback); Both methods appear to function properly, prompting me to inquire whether I can omit the __dirname prefix, ...

What is the best way to organize this list in Python?

Here is the array I am working with: [14, 'S', 12, 'D', 8, 'S', 9, 'S', 10, 'D'] My goal is to sort it in descending order based on numbers while also keeping each number with its respective letter follow ...

Interpret a JavaScript array response

Currently, I am working on an API request where I receive an HTTP response that contains an array with a single JSON object. However, when attempting to parse or stringify it using the following code: var response = http.response; try{ var json = J ...

I need to confirm the existence of two columns, "name" and "group", in my database. If they are found, I want to display a message saying they already exist. If they are not found

How can I modify this HTML with AJAX to display a successful message and insert into the database, but also show an error message if the name already exists after validation? <form action="" id="manage-project"> <label for=&qu ...

Storing selected items in a CheckedListBox as an array in VB.NET

I have been successfully storing all checked items in a string, but now I want to store them in an array along with their names. Here is the code I am currently using: Dim i As Integer Dim ListItems As String ListItems = "Checked Items:" & Control ...

The Angular directive ng-if does not function properly when trying to evaluate if array[0] is equal to the string value 'Value'

In my code, I want to ensure that the icon is only visible if the value at array index 0 is equal to 'Value': HTML <ion-icon *ngIf="allFamily[0] === 'Value'" class="checkas" name="checkmark"></ion-icon> TS allFamily = [ ...

Adapting CSS styles according to the height of the viewport

Goldman Sachs has an interesting webpage located here. One feature that caught my eye is the header that appears as you scroll down, with squares changing from white to blue based on the section of the page. I'm curious about how they achieved this ef ...

What is the best way to link a stylesheet to the content generated by res.write in Node.js?

Currently, I am running a node.js program that performs certain functions and generates an HTML table using res.write(). The output is displayed on the localhost port without being connected to an actual HTML page. As a result, I am facing the challenge of ...

Utilizing Vue.js to share a single array of data across two distinct input lists

For a clearer understanding of my requirements, I have put together a demo on JSFiddle: https://jsfiddle.net/silentway/aro5kq7u/3/ The code snippet is presented below: <script src="https://cdn.jsdelivr.net/npm/vue"></script> <div id=" ...

`How can I update a textbox's value using JQuery Ajax?`

Currently in the process of implementing an ajax call to update the value of a textbox: <div id="PNIncrementDiv" style="position:absolute; left: 730px; top: 15px; width: 350px;" class=""> <input id="TBIncrementTextBox" class="textbox" type="te ...

Searching for a specific bus stop within an array based on a designated route

There's an issue at hand. We have a route with several bus stops. We need to determine the next stop on this route. The "_stopNum": "1" indicates that the stop is the first one on the route. Take a look at a stop example: { "route": [ { ...