Enhance your TypeScript arrays using custom object equality functions

I am looking to utilize array functions such as contains and unique, but I want them to compare equality using my custom equals function.

For instance:

let arr = [{id:1,..//some more},{id:2,..//some more},{id:3,..//some more}]

I need the following code to return true by using an equals function that checks only the id property:

arr.contains({id:1,....}).

I have attempted to search for a solution but haven't been successful.

How can I achieve this? And in general, how can I implement my own equal function in TypeScript (similar to the equals function in Java).

Answer №1

When it comes to array functions like includes or indexOf, the equality check cannot be altered. However, there are other array functions that allow you to implement a callback instead:

  • find - Identifies the first entry in the array that satisfies your callback function's condition
  • findIndex - Determines the position of the first entry in the array for which your callback returns true
  • some - Iterates through the array, executing your callback until a truthy value is returned (at which point, some stops and returns true); if no truthy value is returned by the callback, some will return false.
  • every - Goes through each element of the array, invoking your callback until a falsy value is returned (in this case, every halts and returns false); if the callback never produces a falsy value, every returns true.

All these functions have detailed explanations with links available on the MDN array page.

For instance, using custom equality to find if an array contains certain elements can be achieved with the some function:

const a = [
  {id: 1},
  {id: 2},
  {id: 3}
];
console.log("Has 1? " + a.some(e => e.id == 1));
console.log("Has 4? " + a.some(e => e.id == 4));

Answer №2

You have the option to utilize the find method and verify that the returned value is not undefined.

For instance:

let myList = [{id: 1, value: 'Apple'}, {id: 2, value: 'Banana'}];
const checkIdOne = item => item.id === 1;
const hasIdOne = myList.find(checkIdOne) !== undefined;

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

Mapping a response object to a Type interface with multiple Type Interfaces in Angular 7: A step-by-step guide

Here is the interface structure I am working with: export interface ObjLookup { owner?: IObjOwner; contacts?: IOwnerContacts[]; location?: IOwnerLocation; } This includes the following interfaces as well: export interface IObjOwner { las ...

Expanding interfaces dynamically in Typescript

Currently, I am facing a challenge while attempting to integrate an existing React Native module equipped with the following props: useComponent1: boolean useComponent2: boolean This is how the implementation looks like: render(){ if(useComponent1){ ...

Can the getState() method be utilized within a reducer function?

I have encountered an issue with my reducers. The login reducer is functioning properly, but when I added a logout reducer, it stopped working. export const rootReducer = combineReducers({ login: loginReducer, logout: logoutReducer }); export c ...

Interact with AJAX form to dynamically display result data in the intended DIV

Seeking assistance from experienced JS users! Although most features are functional, including results being returned and forms submitting to MC database, I am encountering an issue where the result html is appearing in the incorrect DIV. Instead of displ ...

Angular 14: A collection and schematic must be provided for execution to proceed with the process

I've recently started learning angular. After installing the latest version, I created an app called "test" using the command ng new test. Next, I opened the app in Visual Studio Code and tried to create a new component by entering the command: ng g ...

Can one utilize generic parameter value within a conditional type result field in Typescript?

Trying to create a versatile function type for data transformation can be a bit tricky. When dealing with a single object, it's straightforward: export type SingleObjFunction<InputDataType, OutputDataType> = (object: InputDataType) => Outpu ...

The optimal method for loading CSS and Javascript from an ajax response within a JavaScript function - Ensuring cross-browser compatibility

I am in a situation where I need jQuery to make sense of an ajax response, but due to latency reasons, I cannot load jQuery on page load. My goal is to be able to dynamically load javascipt and css whenever this ajax call is made. After reading numerous a ...

Watchable: Yield the outcome of a Promise as long as watching continues

I am looking to create a function in Angular and TypeScript that will return an Observable for subscription. This Observable should emit the result of a Promise every three seconds. Currently, I have a function that returns a Promise, but I need it to ret ...

Ways to set the className prop for all components automatically without having to specify it repeatedly

One challenge I face is dealing with code duplication whenever I create a new component. Is there a way to pass the className property between components without having to explicitly define it every time a new component is created? For example, when I cr ...

Time picker in Bootstrap - Ensuring end time is not earlier than start time validation

How to prevent users from selecting a past time for the end time in Bootstrap time picker with start time validation <html> <head> </head> <body> <link href="https://maxcdn.bootst ...

Looking to adjust the HSL of individual colors on a JavaScript canvas, similar to editing in Photoshop?

I'm looking to manipulate the HSL of an image using Javascript. I don't want to apply changes to the entire image at once, but rather target specific color sets like blues and yellows, similar to how it's done in Photoshop. What type of da ...

Utilizing Angular 7, Ngrx, and Rxjs 6 to efficiently share state data among lazily loaded modules

Currently, I am working with Angular 7 alongside Ngrx and Rxjs 6. In my project, I have two lazy loaded modules named A and B, each with its own selectors and reducers. The challenge I am facing is accessing the data stored in module B's state from m ...

Tips on dividing and recycling mongodb connection in Node.js

I am currently troubleshooting the connection to MongoDB using Node.js. The code I have in a file named mongodb.js is as follows: const mongoClient = require('mongodb').MongoClient; const env = process.env.NODE_ENV || 'development'; co ...

Issues with changing background colors using Jquery animate

I am attempting to create a fading background color effect when a button is clicked. Currently, I can change the background color using this code: $("#" + lblqty).css("background","#e9f1ff"); However, when I try to use the animate function as shown below ...

Connecting the SignalR client to various servers

I am currently incorporating SignalR version 2.x into my ASP.Net MVC application, which is also using the same version of SignalR in my Angular client app. The ASP.Net MVC application is hosted at http://localhost:42080, while the Angular app is hosted at ...

"Step-by-step guide on using JavaScript to print a PDF file stored locally

As an illustration, I have a local PDF file with 6 pages. When using the window.print() function, only one page is displayed in print preview regardless of what is shown in the browser. Instead of just one page, all pages should be visible in print previ ...

Whenever I press a button, my card holder gradually slides downwards

I'm facing an issue with my code and I'm unsure whether it's related to CSS or JavaScript. Whenever I click the button on my page, my card-container2 moves downward unexpectedly. Here is the snippet of my code: HTML: <div class="car ...

Tips for continuously prompting the user until a valid answer is obtained, and how to repeat this process N times

I am currently working on a program that displays the digit in the array based on the number the user inputs. Everything is working smoothly, except for a scenario where the user enters a number that is not in the array and then inputs a number that is i ...

My function won't get called when utilizing Angular

My Angular code is attempting to hide columns of a table using the function shouldHideColumn(). Despite my efforts, I am unable to bind my tags to the <th> and <td> elements. An error keeps popping up saying Can't bind to 'printerColu ...

Here is a method to transform the JSON object into a string as demonstrated below:

Presented below is a JSON object: { "category": "music", "location": { "city": "Braga" }, "date": { "start": { "$gte": "2017-05-01T18:30:00.000Z" }, "end": { "$lt": "2017-05-12T18:30:00.000Z" } } } I am looking t ...