Verify if an item is present within a separate array

To determine if an object in one array exists in another array, we can use the combination.some() method with a condition that checks for a match based on specific criteria. In the example below, the event array returns true while the event1 array returns false.

combination.some(a => event.every((v, i) => v.code == a[i].code))

let combination = [
  [
    { code: "repeatAdh", value: null },
    { code: "duplicatePartner", value: null }
  ]
];

let event = [
  { code: "repeatAdh", value: "Répéter adhérent par carte" },
  { code: "duplicatePartner", value: "Répéter conjoint" }
];

let event1 = [
  { code: "duplicatePartner", value: "Répéter conjoint" },
  { code: "repeatAdh", value: "Répéter adhérent par carte" }
];

Answer №1

In Javascript, comparing the value of different objects does not have a built-in method.

When comparing two objects in Javascript, the comparison is based on whether they are 'the same' object by identity rather than value.

For example, consider these two objects which are not the same:

const a = { foo: 'bar' };
const b = ( foo: 'bar' };

a === b // false

However, these two objects are the same:

const a = { foo: 'bar' };
const b = a;

a === b // true

If you add a property to a in the second example, it will also appear in b.

To compare two objects by value, one must examine each property and ensure that they all match.

Answer №2

Comparing objects in JavaScript can be quite challenging as there is no straightforward built-in function for it. It's important to first define what "equals" or "exists" means in the context of your specific situation.

For instance, if you know that the objects you want to compare always have identical keys, you could consider them equal if their values match. Here's an example:

function checkEquality(obj1, obj2) {
    return (
        obj1.code === obj2.code && obj1.value === obj2.value
    )
}

You can then create a function to check this equality for each element in a list:

function listEquality(list1, list2) {
  return list1.every(item1 => 
    list2.reduce((acc, item2) => 
      acc || checkEquality(item1, item2)
    , false)
  );
}

By comparing the `event` object with `event1`, the result would be `true`:

listEquality(event, event1)
> true

You can also use this function to determine if an `event` exists in a list of `events`:

function isInList(targetObject, objectList) {
  return objectList.some(object => listEquality(targetObject, object));
}

isInList(event, combination)
> false

isInList(event1, combination)
> false

isInList(combination[0], combination)
> true

If your comparison requirements are more complex, utilizing established solutions from libraries like lodash might be more beneficial. Lodash offers functions such as isEqual and isEqualDeep for checking object equality. You can find more information in the documentation.

I hope this explanation proves helpful.

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

Capturing page titles accurately for timeonsite tracker in a single-page Angular app is challenging when navigating to other pages

Implemented the timeonsite JS tracker in my Angular web application using HTML tags as shown below, <script type="text/javascript"> var Tos; (function(d, s, id, file) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementByI ...

Exploring the world of Typescript TSX with the power of generic

Introducing JSX syntax support in Typescript opens up new possibilities. I have an expression that functions smoothly with traditional *.ts files, but encounters issues with *.tsx files: const f = <T1>(arg1: T1) => <T2>(arg2: T2) => { ...

What is the purpose of the .default() method being added to the class constructor in transpiled Typescript code

In TypeScript, I have the following code snippet to create an instance of ConnectRoles Middleware in Express: let user = new ConnectRoles(config); The middleware initialization is expected to be a simple call to a constructor. However, after transpiling, ...

How can I retrieve the selected value from an Angular 2 dropdown menu when it changes, in order to utilize it within a function?

I am currently working on creating a dropdown menu with multiple options. When a user selects an option, I need to make an API call that requires an ID parameter. Inside my component.ts file, I have defined an array containing the values like this: valu ...

Ionic - What is the correct way to import ViewController? - Uncaught (in promise): Error: ViewController provider not found

I have a Popover in my app and I want it to behave differently based on the selected item. I followed the instructions in the Ionic documentation to achieve this. Error: Uncaught (in promise): Error: No provider for ViewController! When I tried adding ...

Using TypeScript, effortlessly retrieve objects within React components based on their keys

I am looking for a way to dynamically choose a React component based on a key within an object import React, {useState, useEffect} from 'react' import ComponentA from '@components/ComponentA'; import ComponentB from '@components/Co ...

Incorporating HTML code within a .ts file: a basic guide

I'm relatively new to Angular, but I've been given a project that's built with Angular. As I examine the .ts file containing the list of property types, I need to wrap a span around the label text. Is this doable? Here is the current list ...

Angular: accomplish cascading requests to achieve desired outcomes

While exploring Angular rxjs operators, I came across a scenario where I need to send requests to the server that depend on each other. Currently, I have a modal window open and during the ngOnInit lifecycle hook, multiple requests are being sent, some of ...

Ways to update the value within an object in an array stored in a BehaviorSubject?

My initial data is: const menuItems = [{id: 1, active: false}, {id: 2, active: false}] public menuSubject$ = new BehaviorSubject<MenuItem[]>(menuItems); public menu$ = this.menuSubject$.asObservable(); I am attempting to update the element with ...

The error message indicates that the argument cannot be assigned to the parameter type 'AxiosRequestConfig'

I am working on a React app using Typescript, where I fetch a list of items from MongoDB. I want to implement the functionality to delete items from this list. The list is displayed in the app and each item has a corresponding delete button. However, when ...

Issue customizing static method of a subclass from base class

Let me illustrate a simplified example of my current code: enum Type {A, B} class Base<T extends Type> { constructor(public type: T) {} static create<T extends Type>(type: T): Base<T> { return new Base(type); } } class A exte ...

Guide on transferring the token and user information from the backend to the front-end

Here is the code from my userservice.ts file export class UserService { BASE_URL = "http://localhost:8082"; constructor(private httpClient:HttpClient) {} public login(loginData:any){ return this.httpClient.post(this.BASE_URL+"/au ...

The TS-Mocha and Chai duo have encountered a hitch: a peculiar error message, TS2695, informing them that the left side of the

Software Versions: "ts-mocha": "^8.0.0", "ts-node": "^10.3.0", "chai": "^4.3.4", Sample Code: expect(wrapper.find(MyListItem)).to.have.length(3); Execution Command: ts-mocha tests/**/*.tsx -r u ...

Optional parameters in typed languages can either have zero or all parameters provided

I am delving into the world of typed functional programming and have embarked on implementing partial application with a focus on type safety. Issue at hand: I'm aiming to create a function that can take a function along with zero or all of its param ...

Eliminate nested object properties using an attribute in JavaScript

I am working with a nested object structured like this const data = [ { id: '1', description: 'desc 1', data : [ { id: '5', description: 'desc', number :1 }, { id: '4', description: 'descip& ...

Developing the headers for a service using React.js

As someone new to ReactJs, I'm curious about the various methods we can use to include Headers in our service Url before making a call. While I'm familiar with how GET/POST Calls are made in angular Js after including headers, I'd like to l ...

I am facing the dilemma of having an identical button appearing in two separate locations. How can I determine which button has been clicked?

I am currently using ng2-smart-table and have implemented a custom filter with the same button in both filters. However, I am unsure of how to determine which button is being clicked. https://i.stack.imgur.com/b1Uca.png Below is the component code for th ...

JavaScript module declarations in TypeScript

Recently, I delved into the world of a Node library known as bpmn-js (npmjs.com). This library is coded in JavaScript and I wanted to incorporate typings, which led me to explore d.ts files. My folder structure looks like this webapp @types bpmn ...

Typescript custom react hook - toggling with useToggle

I developed a custom hook to toggle boolean values: import { useState } from 'react'; export function useToggle(initialValue: boolean) { const [value, setValue] = useState<boolean>(initialValue); const toggleValue = () => setValue ...

Obtaining data from a TypeScript decorator

export class UploadGreetingController { constructor( private greetingFacade: GreetingFacade, ) {} @UseInterceptors(FileInterceptor('file', { storage: diskStorage({ destination: (req: any, file, cb) => { if (process.env ...