Experiencing incorrect outcome when using the Number.isInteger() function in JavaScript

I have been experimenting with the Number.isInteger() method on the Chrome console. After running a for loop and checking the result using console.log(arr);, I noticed that the array only contains a single value of 1, like this: [1];


var arr = [1, 2, 3, 'some', 'string'];

for (var i = 0; i < arr.length; i++) {
    if (Number.isInteger(arr[i])) {
        arr.splice(arr.indexOf(arr[i], 1));
    }
}

Does anyone have any insight into what I might be doing wrong? Any help would be greatly appreciated. Thank you!

Answer №1

You are facing a significant issue where you are continuously deleting items from an array while iterating through it. Each time an item is removed, you need to backtrack by one step (i--).

var arr = [1,2,3,'some','string'];

for (var i = 0; i < arr.length; i++) {
    if (!isNaN(arr[i])) { // To determine if it's a valid number, we have to invert the test since isNaN returns true for non-valid numbers
        arr.splice(i, 1); // If the element at index i is a valid number, remove it (no need to search for the index using indexOf, as we already have it with i)
        i--;              // After removing an element, we must move back one step (otherwise we will skip an item each time we remove another)
    }
}


console.log(arr);

Answer №2

Why not try utilizing the typeof operator instead?

var elements = [1,2,3,'some','string'];
for (var index = 0; index < elements.length; index++) {
  if (typeof elements[index] == 'number') {
    elements.splice(elements.indexOf(elements[index], 1));
  }
}

Answer №3

Using the `.splice()' method directly modifies the original array itself.

Therefore, every time you iterate through the array, its core structure changes.

If your goal is to have only integers in the array:

    var arr = [1, 2, 3, 'some', 'string'];

    var newArray = [];

    arr.forEach(function(element) {
        if (Number.isInteger(element)){
            newArray.push(element);
        }
    });

    console.log(newArray);

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

Sending parameters with the Link component in React

I am working on an index component that is set on the '/' route. Within this component, there is a Link element. Despite successfully redirecting to /search upon clicking the link, I am unsure how to pass parameters with the link and access them ...

The function insertAdjacentHTML does not seem to be functioning properly when used with a

I am working with a parent element that contains some child elements. I create a DocumentFragment and clone certain nodes, adding them to the fragment. Then, I attempt to insert the fragment into the DOM using the insertAdjacentHTML method. Here is an ex ...

Error: Invalid syntax detected: /blog

I am encountering an issue with jQuery while trying to add a blog section to my existing single-page site. The new blog will be located in a separate /blog directory, causing the menu item for it to differ from the other href="#" tags on the index.html pag ...

Utilizing Json data with Jquery for dynamically placing markers on Google Maps

Seeking assistance as I am currently facing a problem where I need to loop through JSON data and add it as markers on Google Maps, but unfortunately, it only returns null value. Is there a way to automatically connect this to JSON? My plan is to have a Gr ...

The mistake in npm install is when the console logs a bug that is notorious for causing npm to malfunction

After reading this article, I successfully installed Node.JS version 9.4.0. $brew install node $node -v $v0.12.7 Next, I ran npm install -g grunt-cli for testing. H ...

Images and text mix with query mobile in a spontaneous array

I am currently working on a piece of code that generates a random image when the initial screen image is clicked (taken from JavascriptSource): <script type="text/javascript"> <!-- Original: Nicholas Lupien--> <!-- Begin var rand1 = 0; var ...

Troubles arise with loading Ajax due to spaces within the URL

I currently have two python files named gui.py and index.py. The file python.py contains a table with records from a MYSQL database. In gui.py, there is a reference to python.py along with a textfield and button for sending messages. Additionally, the g ...

Is accessing out-of-bounds in Python secure? Is it considered poor practice?

> [1, 2, 3][1:int(1e9)] [2, 3] As someone with a background in C, the code above initially caused me some concern. However, it appears to function as intended. Can this code be relied upon to work consistently in all instances of python3? Is it as effi ...

Script for tracking user activity on Facebook and Google platforms

I currently have Google tracking conversion set up, but now I also need to implement Facebook pixel tracking. My existing Google Head Script code is as follows: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||fu ...

Every time I attempt to execute this piece of code in "node.js", an error pops up

const express = require('express'); const request = require('request'); const bodyParser = require('body-parser'); const https = require('https'); const app = express(); app.use(express.static('public')); ...

Tips on displaying a confirmation box when the page is refreshed or closed

I need to implement a confirmation box for users who try to close the window without saving the content of a textarea within a form. Here is the code I currently have: var myEvent = window.attachEvent || window.addEventListener; var chkevent = window.att ...

Using Vue.js to implement dynamic table rowspan functionality

Has anyone experimented with implementing dynamic table rowspan in vue.js? Here is the sample data { date: '2018-08-14', temp_que : 120, }, { date: '2018-08-14', temp_que : 120, }, { date: '2018-08-15', ...

Issue encountered when running a minification build on Angular 5

After successfully updating my Single Page Application (SPA) from Angular 4 to Angular 5 along with all dependencies, everything seemed to be working well. Both the development and production builds were functioning without any errors or warnings. However ...

Access the contents of a URL using PHP

I am attempting to create a PHP array from a URL string. Here is my code: $files = urldecode($_POST['files']); // The String error_log($files); // Outputting to see the format parse_str($files); // parsing... error_log($files[0]); // Viewing th ...

Converting and saving geometry in three.js using the toJSON method and BufferGeometryLoader for serialization and deserialization. Transmitting geometries as text

Let me start by saying that I am new to three.js and would like to share my learning journey. My objective was to convert geometry into a format that can be transferred to another web worker (as not all objects can be transferred between workers, only s ...

The JSON array object gets replaced in the local storage

I have been working on a form page where there are 3 input fields: "fname," "emailId," "phoneNo." Every time a user enters details in the form, I am storing them in localStorage. However, the object keeps getting overwritten. Here is the script: <scri ...

Unlock the potential of HTML5 Datalist: A comprehensive guide on integrating it with

The latest version of HTML, HTML5, has introduced a new tag called datalist. This tag, when connected to <input list="datalistID">, allows for autocomplete functionality on web forms. Now the question arises - what is the most efficient approach to ...

Mastering the utilization of custom input events in PrimeNG with Angular

I am currently working on an Angular 16 project. Within this project, I have implemented a number input field that is being validated using formControls. To make my work more efficient, especially since this input is used frequently, I decided to encapsula ...

Verify the presence of a JSON object in Postman

I'm looking to create a test in Postman to validate the presence of JSON keys in the server response I've received. Here is the response: { "Result": 0, "ResponseStatus": { "ErrorCode": null, "Message": null, "StackTrace": null ...

|Webview|Best Practices for Integrating Upload Script

I am currently developing an Android app using WebView and I need to implement a code for uploading on Android. I came across the following code snippet and I want to convert it into JavaScript instead of Java (if possible). It needs to be linked to the up ...