A solution for Array.includes to handle NaN values

While browsing some Javascript blogs, I stumbled upon the Array prototype methods .indexOf and .includes. I noticed that if an array includes NaN as a value, indexOf may not be able to detect it, leaving us with the option of using .includes. However, considering that includes is not supported by IE, what can be used as an alternative method to check for NaN? I considered creating a polyfill using the guidance provided here

if (Array.prototype.includes) {
  Object.defineProperty(Array.prototype, "includes", {
    enumerable: false,
    value: function(obj) {
        var newArr = this.filter(function(el) {
          return el == obj;
        });
        return newArr.length > 0;
      }
  });
}

var arr = [NaN];
console.log(arr.includes(NaN));

However, the output is still false. Are there any other alternatives available? Am I overlooking something?

Answer №1

If you want to ensure compatibility for Number.isNaN, you can add a polyfill for it and then incorporate it into your filter test. This way, if both the obj and el values pass the Number.isNaN check, you can return true:

Number.isNaN = Number.isNaN || function(value) {     
    return value !== value;
}

// if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, "includes", {
    enumerable: false,
    value: function(obj) {
        var newArr = this.filter(function(el) {
          return el == obj || Number.isNaN(el) && Number.isNaN(obj);
        });
        return newArr.length > 0;
      }
  });
// }

var arr = [NaN];
console.log(arr.includes(NaN));

Answer №2

Array#includes utilizes the Same-Value-Zero concept, distinct from the == operator.

The Same-Value aspect is explained in Object.is(), allowing manual checking for -0 and +0 to address the "Zero" component of the evaluation.

While the linked resource provides a polyfill, it alters the treatment of -0 and +0, which isn't ideal for a Same-Value-Zero algorithm. Consequently, following a more simplified approach is recommended:

function SameValueZero(x, y) {
    return x === y || (x !== x && y !== y);
}

Answer №3

To locate the position of the NaN in an array, you can utilize the method findIndex. Here is an example of how you can achieve this:

var arr = [NaN];
let index = arr.findIndex(Number.isNaN)
console.log(index >= 0);

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

Differences between using a getter in Vue.js/Vuex compared to directly accessing state values on the create lifecycle hook

As I utilize the created lifecycle hook within vue.js to fetch data from my store and pass it to a vue component's data, an interesting observation arises. When I employ this.selectedType = store.state.selectedType, the data is successfully retrieved ...

Instructions for setting a cookie to conceal a notification bar upon the second page load

I am looking for the following scenario: When a new visitor lands on my website, a notice bar fixed to the bottom of the screen becomes visible. After clicking on a menu item to navigate to another page, a cookie is set upon the second page load. This co ...

What could be causing Node Pdfkit to sometimes generate a corrupted file within my code?

I've encountered an issue with my function that generates a PDF file and sends it via email using `pdfkit` and `nodemailer`. Occasionally, I receive a file that cannot be opened. I'm unsure why this happens sporadically while it works fine most o ...

A guide on extracting data from an uploaded JSON file in a React and Next.js application

Users have the ability to upload a JSON file by clicking on the button provided (shown below). https://i.sstatic.net/jndOd.png Once the JSON file is uploaded, the content is stored into a variable or a state. let fileRef = useRef(); const uploadHandle ...

What is the best way to dynamically load content with AJAX that includes a script?

Currently, I am in the process of developing a website where I am utilizing jquery/ajax to dynamically load content onto the homepage. The test site can be found at [. While the home and about me pages load perfectly, I am encountering an issue with the pr ...

Exploring the utilization of type (specifically typescript type) within the @ApiProperty type in Swagger

Currently, I am grappling with a dilemma. In my API documentation, I need to include a 'type' in an @ApiProperty for Swagger. Unfortunately, Swagger seems to be rejecting it and no matter how many websites I scour for solutions, I come up empty-h ...

Halting the HTML-Embedded Video

Currently, I am utilizing a cross-browser embedding method like the following: <video width="549" height="309" controls poster="video/stills/index_demo_videoScreen.jpg" style="margin-top:20px;"> <source src="video/2014-reel-web.mp4" type="vid ...

What could be the reason for the failure to inject Angular Bootstrap?

How can I incorporate Angular Bootstrap into my AngularJS application correctly? By manually including external versions of the libraries in the index.html file, everything works perfectly with Angular Bootstrap: <!-- start manual dependencies for t ...

Using Chrome.downloads.download within a Chrome application

My app is running into an issue where Chrome is giving me the error message that chrome.downloads is undefined. In my attempt to download an image, here is a simple example provided... Here is the manifest: { "manifest_version": 2, "name": "Download ...

Updating object values within a while loop using JavaScript

I am facing an issue with managing an array of JavaScript objects that have a property 'table' with values table1, table2, table3, or table4. Each table should only accommodate 6 members. I have implemented a while loop to check if 'table1&a ...

Error with SwitchMap on ActivatedRoute.paramMap

When I try to run the ngOnInit method of my component, I encountered an error with the following line of code. this.products$ = this.route.paramMap.switchMap((params: ParamMap) => this.getProductsForType(params.get('type'))); The error mes ...

Managing the state of dynamically generated tabs within a NextJS application

Looking to develop a web app in Next.js that includes tabs components. The goal is to manage various entities within each tab, such as utilizing a search bar to select different products. Upon selecting a product, a new tab will be generated with the produ ...

Instructions for utilizing img.shape() in Javascript

import cv2 open image file img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED) fetch image dimensions dimensions = img.shape image details height = img.shape[0] width = img.shape[1] channels = img.shape[2] print('Image Dimensi ...

Sending parameters in GraphQL with Typescript results in an empty set of curly braces being returned

I am new to learning GraphQL with Typescript and I am trying to pass an argument in a GraphQL function to return something dynamically. I have been struggling with this issue for the past hour and could not find any solutions. Here are the relevant code sn ...

Exploring the syntax of ReactJS state management with setState

Trying to wrap my head around the following syntax in my React app. I am looking to understand how the code inside setState() works. this.getSomePromise().then( // resolve callback function someImg => this.setState(prevState => ( ...

Combining outcomes from two separate jQuery AJAX requests and implementing deferred/promise functionality

I am struggling to combine the outcomes of two jQuery AJAX requests. Despite reviewing similar questions here, none seem to provide a solution. Each ajax call (2 in total) has a success function that calls the createStatusView function and passes it the ...

Having trouble with Node.js GET request functionality not functioning properly

I've been encountering difficulties with loading a page using Node.js. While my Node.js Application code functions properly when attempting to load other resources such as www.google.com, it seems to encounter issues specific to the domain name www.eg ...

Troubleshooting an Ajax Error

Encountering an issue when trying to bind two components (checkbox and label) by using the "for" tag attribute for the label and the "id" tag attribute for the checkbox. An ajax debug error is thrown: "Cannot bind a listener for event "click" on element "v ...

OBJ and MTL Loaders from Three.js are not being continuously invoked

I'm currently using the THREE.js OBJ and MTL Loader in a loop to display various elements of a 3D animated cake. I specifically need these elements so that users can change the color of certain parts (e.g. decorations) of the cake. However, I've ...

The state value is not preserved after redirecting to another page

For the past couple of days, I've been struggling with an issue and I can't seem to figure out what I'm doing wrong. My goal is to create a login page that redirects users to the dashboard after they log in. To maintain consistency acros ...