What is the reason behind the return value of -1 when using .indexOf()?

function mutation(arr) {
         var total = arr.map(function(x){return x.toLowerCase();});
          var sec = total[1];
            for(var i=0; i < sec.length; i++){
        //       console.log(sec[i]);
              console.log(total.indexOf(sec[i]));
          }
        }
        mutation(["hello", "hey"]);

I am seeking some clarification on this. Can someone help me with it, please? The line with

console.log(sec[i]);

displays each letter of the 'hey' string one by one in the console. This seems to be working fine. However, I'm puzzled by why calling 'sec[i]' in

console.log(total.indexOf(sec[i]));

always results in outputting '-1', indicating that the .indexOf() method couldn't find any matching letter!

Answer №1

Comparing the total array to a single character leads to unequal lengths, as a string with a length greater than one cannot be equal to a single character (string length 1).

In essence, it boils down to this:

["hello", "hey"].indexOf('h') // -1
["hello", "hey"].indexOf('e') // -1
["hello", "hey"].indexOf('y') // -1

If you intend to compare the first string with the characters of the second, you must specify the index.

console.log(total[0].indexOf(sec[i]));
                 ^^^

function mutation(arr) {
    var total = arr.map(function (x) { return x.toLowerCase(); }),
        sec = total[1],
        i;

    for (i = 0; i < sec.length; i++){
        console.log(sec[i], total[0].indexOf(sec[i]));
    }
}

mutation(["hello", "hey"]);

Answer №2

The search yielded no results, hence the returned value of -1.

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

I'm having trouble loading my Google Maps widget. Everything was functioning flawlessly until I attempted to hide it using the .hide function

After successfully implementing a Google Maps widget, I encountered an issue when trying to toggle its visibility using jQuery. Despite clicking on a div element to reveal the widget, the map fails to load inside the designated container. It seems as tho ...

Is your React Native list elements feeling a little too close for comfort?

I'm facing an issue where the items in my list are not properly spaced out and I'm unable to figure out why. I have 3 elements for each letter that should be separated from each other. I suspect that the issue might be related to the fact that th ...

The function for converting a jQuery element to a DOM element is yielding a blank string as

What is the reason behind this code not working as expected: function getElementWidth(el){ return $(el)[0].style.width }; getElementWidth('#someElementIdId'); // returns -> "" However, when using this code... function getElementWidth(el){ ...

The jQuery autocomplete feature seems to be malfunctioning and not displaying

Here is the code snippet I am working with: <div class="input-group"> <form method="POST" id="id1"> <input id="id2" type="text" style="min-width: 370px;" class="form-control" placeholder="..."> </form> </div> ...

Guide on importing a Blender scene into three.js with textures, lighting, and camera

I successfully exported a single object (box.json) and scene (box2.json) from Blender using io_three. Additionally, I was able to load a single object (box.json) with textures using JSONLoader() in the modelWithTexture.html file. My goal is to load an ent ...

Stacked column tooltip displaying an array of 3 values

I am working with a json code that looks like this: [[1385420403000,9.86,6.91],[1385506802000,11.89,6.57],[1385593203000,14.11,10.58],[1385679602000,9.1,8.9],[1385766003000,13.59,7.53],[1385852402000,10.68,6.69],[1385938803000,11.03,10.52],[1386025202000, ...

Unit testing with Jest involves creating mock implementations of IF conditions within functions to ensure complete code coverage

Currently, I am working with an API script stored in a file. const ApiCall = { fetchData: async (url) => { const result = await fetch(url); if (!result.ok) { const body = await result.text(); // uncovered line throw new Error(`Err ...

Why is it that JavaScript files are not fetched when injecting HTML into the DOM?

Currently, I am developing a login process and initiating an ajax post request from the browser. After performing some logic to verify the user’s credentials in the backend using asp.net core, I return a view which represents the application's homep ...

Ways to choose tags that do not contain a particular tag within them

I am trying to utilize querySelectorAll to select all i elements that do not contain a font tag. The selector I attempted is: document.querySelectorAll('i > *:not(font)') <i> <font color="008000">Here goes some text</fon ...

Nodejs application encountering a problem with the findUser method in Active Directory

I have encountered an issue while using the activedirectory npm package with Nodejs v16.18.1. The code snippet below is used for authentication and finding user details: Could someone please assist with this? async authUserActiveDirectory(usernameAD: stri ...

Sinon and Chai combination for testing multiple nested functions

I attempted to load multiple external JavaScript files using JavaScript. I had a separate code for the injection logic. When I loaded one JavaScript file, the test case worked fine. However, when I tried to load multiple JavaScript files, the test case FA ...

Graph is not showing up when navigating through page

On my List page (List.Html), users can select multiple rows to display the data in a chart using C3. However, when clicking on the compareList() button to navigate to the Chart page (Chart.Html), the chart does not display properly. It seems that the chart ...

The collapse feature of Bootstrap 4 Navbar is unresponsive

Struggling with the Bootstrap 4 navbar collapse feature issue. In the mobile viewport, instead of collapsing, it displays items as a vertical list. Here is the code snippet: <html> <body> <!-- Navbar --> <nav class="navbar na ...

Having trouble getting AngularJS ngCloak to function properly?

My post category page is supposed to display a message if there are no posts. However, the HTML appears briefly when the page loads and then hides. I thought using ngCloak would solve this issue, but it doesn't seem to be working for me. Here's t ...

JavaScript function not executing

Within a panel in an UpdatePanel, there is both a dropdown list and a file upload control. The goal is to enable the Upload button when a value is selected from the dropdown and a file is uploaded. This functionality is achieved through a JavaScript functi ...

"Does anyone know of a specific jQuery function that allows for mapping a collection, where the `end`

I have a query that searches for specific elements within a selected area: $(some_selector_here).find("ul li.active a span") I am looking for a function that can loop through this collection of elements and provide access to the complete stack of base el ...

The file reader feature is currently experiencing issues on both Chrome and Internet Explorer browsers

After uploading an image file from my PC, I convert it to a data URL and then use the img element to preview it. Surprisingly, this process works perfectly fine in Firefox. However, when I try to do the same in Chrome or IE, the src attribute of the img el ...

How can we identify context menu events triggered by touch actions?

In my application, I have implemented drag-and-drop functionality for elements within an SVG element using d3-drag and d3-zoom. However, on touch-enabled devices such as IE11, Edge, and Firefox, a context menu pops up after a long press, which interferes w ...

Generate a fresh object with distinct identifiers

I am interested in creating a new object, utilizing unique keys consisting of comma-separated IDs. For instance, I have: const d = { "1,2,3,4,5,6,7,8,9,10": [ "created_by", "modified_on", "external_o ...

A guide to removing functions from the render method

Greetings! Currently, I am in the process of creating a simple webpage that utilizes a map function to display all details to the user. Some fellow developers have advised me to remove my functions from the render method, as it continuously renders unneces ...