Typescript code encountering unexpected behavior with Array.includes()

Below is a snippet of TypeScript code from my NextJS application:

const holeSet:any[] = [];
.....

let xx = 1, yy = 2;
holeSet.push({x:xx,y:yy});

xx = 3;
yy = 4;
holeSet.push({x:xx,y:yy});

holeSet.map((e) => {
  console.log("element ::"+JSON.stringify(e));
});

const a = 1;
const b = 2;

if (holeSet.includes({x:a.toString(),y:b.toString()}))
  console.log("Value {1;2} FOUND !");

Upon executing the code, the following output is generated:

element ::{"x":1,"y":2} element ::{"x":3,"y":4}

Despite expecting the message: Value {1;2} FOUND !

to be displayed, it doesn't appear. What am I doing incorrectly?

Could this be due to a syntax error within the if statement?

Answer №1

Utilizing object literal syntax generates a fresh object. For instance, in the provided code snippet:

holeSet.push({ x: xx, y: yy });
//           ^^^^^^^^^^^^^^^^

and

if (holeSet.includes({ x: a.toString(), y: b.toString() }))
//                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

...these produce new, distinct objects.

Array.prototype.includes() utilizes same-value-zero equality to compare the first argument with each array element (referred to as the SameValueZero algorithm in the specification). Two unique objects will never be equal to each other based on that algorithm, thus... by using object literal syntax to create the first argument value when calling holeSeet.includes, it will always result in false:

holeSet.includes({ x: a.toString(), y: b.toString() })
//               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Employing a unique object for this argument will consistently return `false`

You can utilize Array.prototype.some() to check if any of the elements have the expected structure by utilizing a function that compares the property values of x and y to the expected values:

if (holeSet.some((o) => o.x === a && o.y === b))

Code in the TypeScript Playground

This will cause the condition to evaluate to true and the expected message will be displayed in the console.

Answer №2

The issue occurring here is due to the way includes function operates. When comparing objects, they are compared based on reference, not value. Therefore, it is trying to determine if it is the exact same object, which it never will be. To fix this, you can utilize the following technique:

holeSet.some(e => e.x === a && e.y === b)

By using this approach, you can compare the values of each object in the array, which I believe will yield the desired outcome similar to what you expect from includes function.

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

Deactivate the signup button automatically when the user is not present, without the need to refresh

To determine user availability, the system will check the table of users. If the user is available, the signup button will be displayed; otherwise, the button will remain disabled or its color may change. ...

Require assistance in understanding JSON data in the form of a variable

Apologies for any language barriers, but I have encountered a problem that I need help with. I am trying to create a highchart from an AJAX call. The following code works perfectly: chartOptions = { chart: { renderTo: 'grafica1', type: 'ar ...

ng-click-outside event triggers when clicking outside, including within child elements

I am looking to trigger a specific action when I click outside of the container. To achieve this, I have utilized the ng-click-outside directive which works well in most cases. However, there is one scenario where an issue arises. Inside the container, the ...

Ways to invoke a controller function from a window listener function

Is there a way to trigger the close function from window.onbeforeunload even when closing the app through 'right click' -> 'close window'? It seems that this.close() is not working in this scenario, possibly due to scope issues. The ...

Steps to temporarily turn off Backbone.sync for a fresh model and then reactivate it once the user clicks the save button

I am currently working with a Backbone collection model that consists of sub-models as elements, along with views to edit it. My objective is to have the syncing functionality "turned off" initially when the model is created, so that the back end is not c ...

Leveraging LESS in an Angular2 component

Currently, I am attempting to integrate LESS with angular2. To do so, I have imported the less.js file in my index.html and I am using the following command within the component: less.modifyVars({ '@currentTheme-bar': '@quot ...

Can a single shield protect every part of an Angular application?

I have configured my application in a way where most components are protected, but the main page "/" is still accessible to users. I am looking for a solution that would automatically redirect unauthenticated users to "/login" without having to make every ...

"Troubleshooting issue with jQuery failing to identify PHP variable within an if

I have managed to implement a code that utilizes jQuery and PHP session to add items to the cart. Everything is working smoothly except for displaying the status of the action, such as "Added to cart" or "Updated". The message about the status is stored in ...

The body classList variable is inaccurately updated when making a JQuery Ajax call

Currently, I am in the process of developing a script to manage Ajax page transitions using JQuery's Ajax request function. Within the success callback of the Ajax function, it is essential for me to access the classList of the current page's bod ...

Using the Unleash Feature server in a browser for React projects: A step-by-step guide

I'm currently working on implementing the unleash feature toggle in my React Project. Everything is running smoothly with the backend server (thanks to the Java SDK), but I've hit a roadblock when it comes to making unleash requests from the brow ...

Setting up TypeScript in Jest without the need for webpack

Currently, I'm developing an NPM module using TypeScript without the use of Webpack for compiling scripts. I need some guidance on configuring Jest to properly run tests with TypeScript files. Any recommendations? // test.spec.ts import {calc} from ...

Place the array contents inside a fresh division labeled "row" once it reaches 4 elements

I'm currently working with Bootstrap and I want to display my output in a specific grid format. I have successfully grouped my array into piles of 3 and placed them in a div with the classname "row". However, I'm facing an issue where the element ...

Tips for creating unit tests for my Angular service that utilizes the mergeMap() function?

As a beginner with the karma/jasmine framework, I am currently exploring how to add a test case for my service method shown below: public getAllChassis(): Observable<Chassis[]> { return this.http.get('chassis').pipe( merge ...

What is the best way to conditionally render table data in React JS using a loop?

Currently, I'm working on a project with React.js and facing challenges in iterating through a data array to selectively render elements based on each data node's properties. The dataset is structured as follows: var requests = [ {"id": ...

Encountering a 404 (Not Found) error when attempting to make an API call in React JS with Azure MVC

When trying to make a POST API call from my React app to an Azure MVC controller, I encountered an error in the console: POST http://localhost:3000/api/SampleData/AcknowledgeRole 404 (Not Found) This error is puzzling because I have clearly defined the ...

PHP: When an Array Key is Not Defined

https://i.sstatic.net/k2d1Z.png This is the result I am trying to organize and display my data in tables based on the date. I have stored the data from the database in an array for this purpose. However, I am encountering an error warning stating 'un ...

Tips for expanding the functionality of the d3-selection module using TypeScript

I am currently working on a project that involves TypeScript and d3. I have already installed 'd3' and '@types/d3', and my use of d3 looks like this: import * as d3 from 'd3'; const x = d3.scaleLinear ... Everything was goin ...

Why does the MEAN Stack continue to route using the '#' symbol in the URL?

Currently navigating the realm of back end development. Started off by following a guide on express from thinkster. In need of some clarification. Initially, I grasped that front-end and back-end routing serve different purposes. Front-end routing relates ...

Issue with useEffect EventListener in REACT HOOKS

Recently, I attempted to create a simple Snake-Game using REACT. Everything was going smoothly until I encountered an issue with using useEffect for moving the "snake" when a keydown event is triggered. The challenge arose when trying to implement moveSnak ...

Is it possible to modify the parameters of a function by utilizing a MethodDecorator without affecting the "this" value?

Consider a scenario where you need to dynamically modify method arguments using a decorator at runtime. To illustrate this concept, let's simplify it with an example: setting all arguments to "Hello World": export const SillyArguments = (): MethodDec ...