Unconventional Quirks of Equalizing Arrays from Split CSV Strings

Update - It appears that we might be dealing with a localized bug. Further testing is required to confirm...

I have a CSV String (containing spaces) that resembles the following:

var myString = "Here is a value, I am an important value, One last value"

I've split this String into an array using

var myArray = myString.split(", ")
. The values in myArray are as follows:

// myArray[0] = "Here is a value"
// myArray[1] = "I am an important value"
// myArray[2] = "One last value"

Now, within a simple for loop, I'm using an if statement to check if "I am an important value" exists in the CSV String like so:

for (var i = 0; i < myArray.length; ++i) {
  if (myArray[i] == "I am an important value") {
    myBool = true;
  }
}

I also tried

if (myArray[i] == 'I am an important value')
and `if (myArray[i].toString() == "I am an important value")` with no success.

The strange part is that the value does exist in the CSV String, they are separated correctly (no trailing spaces), but the condition isn't returning true for some reason. Is there a hidden factor that I'm overlooking? I purposely used == for type conversion purposes. Changing to === didn’t change anything. The loop iterates through each element in myArray and sets myBool to true when it finds the value, so it's perplexing why it's not working immediately.

What's even more peculiar is that I compared the character count of each myArray element to the input String and found them identical. So why isn't the equality comparison acting as expected?

PS - An interesting point about this issue is how a similar approach earlier in the function, maintaining the same input type, works perfectly fine. If, for instance, I remove "Here is a value" from the original CSV String, then the condition evaluates to true and myBool switches to true (as long as the comparison value is the first element). Otherwise, it fails to do so.

PPS - The individual values in the original CSV String won't contain commas, hence myString.split(", "); suits the purpose.

UPDATE: On separating the function into its script file and running tests, an unexpected behavior surfaced (what exactly is String.split() doing?)

/*
* This illustrates the data setup within my script. An Object holds a String property.
* The object itself is passed as a parameter, upon which I perform checks:
*/

function start() {

  var myObject = {
    "property": "Here is a value, I am an important value, One last value",
    "extra": false,
  }

  var result = stringSplitTest(myObject);

  Logger.log("Result: " + result);
}


function stringSplitTest(someObject) {

  var myBool = false;

  var stringToSplit = someObject.property;
  Logger.log(stringToSplit);

  var array = stringToSplit.split(", ");

  for (var i = 0; i < array.length; ++i) {
    Logger.log("Index " + i + ": " + array[i]);

    if (array[i] == "I am an important value") {
      myBool = true;
      break;
    }
  }
  return myBool;
}

Logging output:

[13-07-25 11:29:45:628 EDT] Here is a value, I am an important value, One last value
[13-07-25 11:29:45:628 EDT] Index 0: Here is a value
[13-07-25 11:29:45:628 EDT] Index 1: I am an important value
[13-07-25 11:29:45:628 EDT] Result: true

Answer №1

It seems like your code is functioning correctly in Google Apps Script (GAS) as well. Since you mentioned that it utilizes pure JavaScript, the problem probably lies elsewhere.

Here's a GAS function for testing:


var myString = "This is a sample string, I represent an important value, The last one",
    myArray = myString.split(", "),
    myBool = false;

function test(){
    for (var i = 0; i < myArray.length; ++i) {
        if (myArray[i] == "I represent an important value") {
            myBool = true;
            break;
        }
    }
    Logger.log(myBool);
}

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

Node.js - Error: Undefined:0 SyntaxEncountered an unexpected end of input syntax error

Exploring Node.js and Backbone.js for the first time. Using the book "Backbone Blueprints" but encountering issues with the provided code to set up the webserver. Node.js is installed and running fine. Here's the package.json code: { "name": "simp ...

The Angular service uses httpClient to fetch CSV data and then passes the data to the component in JSON format

I'm currently working on an Angular project where I am building a service to fetch CSV data from an API server and convert it to JSON before passing it to the component. Although the JSON data is successfully logged in the console by the service, the ...

Create a panoramic view using six images using Three.js and WebGL

After successfully building a panorama with three.js using the CSS3D renderer, I am now looking to achieve the same result using the WebGL renderer. When working with CSS3D, I utilized the following code to create a seamless panorama: var sides = [ { url ...

Producing numerous results from a single input

How can I ensure that users input their address correctly, including street, number, entrance, floor, and apartment, into a single form field without missing any of the values? Additionally, how can I then extract each value (street, number, entrance, floo ...

Choose items from an array using a checkbox form in PHP

I attempted to generate a form using an array, allowing the items to be selectable and collected individually as variables for processing. However, when I try to echo $_POST['citem1'], I end up with a blank screen. <?php foreach($_SESSION[&ap ...

Combining an Image with a CanvasJS Graph and Generating a Downloadable Image of the Composite

I am attempting to combine an image (a background image for my graph) with my canvasJS chart. Once these elements have been merged on a canvas, I aim to obtain a DataURL of this canvas, enabling me to download an image of it (depicting the graph along wit ...

Conducting a directory verification process using Node.js

Is there a method to execute a server script that verifies the presence of all necessary directories in the server directory? I have explored using server.on('event') but it appears that this specific event does not exist. ...

Accessing PHP output within Jquery

Even though I know PHP is a server-side script and JavaScript is client-side, I encountered an issue. I struggled to bypass browser security when making an AJAX request to another domain. Feeling lost, I decided to turn to PHP for help. The challenge I f ...

Display JSON values in sequence using Material-UI animations

I have received an array of JSON data from the API that looks like this: "fruits": [ { "id": "1", "fruit": "APPLE", }, { "id": "2", "fruit": ...

Steps to create a submit button that is linked to a URL and includes an image

I'm attempting to convert my submit button into an image that, when clicked, redirects to another page. Currently, the submit button is functional but lacks the desired image and href functionality. <input type="submit" name="submit" alt="add" o ...

Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the lis ...

Direct users to a different page upon reloading the page in Django

Currently working on a web application with the Django framework. In one of the forms in my app, I am looking to automatically redirect to a new page upon reloading the current page, rather than when the form is submitted. Any insights from the community w ...

When json.parse encounters an undefined value at position 1

Currently, I am diving into learning express.js and my latest project involves creating a web app that can convert cryptocurrency to Fiat currency. Things have been progressing smoothly so far, but I've hit a roadblock when attempting to use json.pars ...

Is there a method to avoid the default state from loading upon the initialization of my AngularJS application?

Context In order to ensure that the user has an authenticated session, my app must send a request to the server before loading the first state. Depending on the URL, if the user is not authenticated, they should be redirected to the login page. For examp ...

What is the best way to access and iterate through JSON data?

I am trying to extract data from my Json file, however, I cannot use a specific 'key' because it changes on a daily basis. https://i.sstatic.net/sZySk.png My attempted solution is as follows: template: function(params) { const objects ...

Personalizing Web Push Alerts (Google Chrome)

I successfully implemented a web push notification for Google Chrome using Google Project and Service Worker. One thing I'm curious about is how to customize or style the push notification. The plain message box doesn't quite cut it for me – I ...

Consider using React Components as an alternative to implementing pagination dots within Swiperjs, as it may help resolve the issue displaying

I seem to be encountering a small issue and I believe I am making a mistake somewhere. How can I replace the default dots with custom elements for pagination in Swiperjs for React? The custom element should return an SVG from an array of icons. Initially ...

Is it possible to load images top to bottom?

Is there a way to make browsers load images from the bottom to the top? Imagine I have an extremely long image that takes 60 seconds to load. The content is designed to be read from bottom to top. Is there any trick I can use to ensure that the image load ...

Encountering MIME type error (text/html) during Angular project deployment

I am facing an issue while trying to deploy a project built with Angular/CLI 6.12.0. After transferring the content of the "dist" folder to a server, I encountered a console error related to MIME type. The module at address "http://www.sylvainallain.fr/p ...

Subset a 2-dimensional array by row to only include rows with a particular value

My goal is to subset 2D arrays of varying dimensions and extract only the columns that contain a 3 using the "any" function. While it works well with multiple columns containing a 3, it fails when there is only one or zero columns with a 3 present. Here&ap ...