Verify if the ID exists in a different array using ES6

I needed to filter the data. My goal was to compare the data in data1 with the data in data2 and check for any error messages. Take a look at my code below. Is there a more efficient way to achieve this?

data1

[
    {
        "ids": "0111",  
    },
    {
        "ids": "0222",
    }
    {
         "ids": "0333",
    }
]

data2

[
  {
    "id": "0111",
    "errorMessages": [
      {
        "message": ["sample error message 1"]
      }
    ]
  },
  {
    "id": "0333",
    "errorMessages": []
  }
]

Code

const filteredData = data1.filter(
  (element) => element.ids === data2.find((data) => data).id
);

console.log("filtered data", filteredData);

Answer №1

.find((data) => data) is not very useful in this scenario because each item in the array is an object, which is always truthy, leading to the first element being returned every time.

If you were looking to use .find to locate a matching element in another array, a more efficient approach would be to create a Set of the IDs found in the other array first. Set lookup has a complexity of O(1), which is much quicker compared to .find with a complexity of O(n).

Additionally, it's important to implement logic to verify if the errorMessages array is empty.

const data1 = [
    {
        "ids": "0111",  
    },
    {
        "ids": "0222",
    },
    {
         "ids": "0333",
    }
]
const data2 = [
  {
    "id": "0111",
    "errorMessages": [
      {
        "message": ["sample error message 1"]
      }
    ]
  },
  {
    "id": "0333",
    "errorMessages": []
  }
]


const ids = new Set(
  data2
    .filter(item => item?.errorMessages.length)
    .map(item => item.id)
);

const output= data1.filter(
  element => ids.has(element.ids)
);
console.log("output", output);

Answer №2

Utilizing an Object instead of a Set for mapping purposes.


const IDKeys = {};

data2.forEach(item => {
    if (item.errorMessages.length){
       IDKeys[item.id] = true; // indicates validity
    }
})


const filteredItems = data1.filter(item => IDKeys[item.id]);

This approach is efficient with O(n) complexity as key access in an object is O(1)

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

Is it possible to modify the geometry in Three.js to match the texture?

Currently, I am immersed in a Three.js project that involves integrating multiple images into a 3D space. My approach so far has been to directly use these images as textures on planes. However, the challenge lies in the fact that these images vary in heig ...

Can you point me in the right direction to find the Configure function within the EasyRTC module for

As a newcomer to NodeJS, I may be getting ahead of myself, but I'm diving into running the EasyRTC demo with NodeJS. On the EasyRTC download page, there are "easy install instructions" that outline the steps required to get EasyRTC up and running smo ...

Surprising outcomes encountered while attempting to load a text file into an array with JavaScript

Currently, I am in the process of developing an emulator and seeking to compare opcode logs from another functional emulator. The log containing executed opcodes is prepared for comparison and follows this format: //log.txt (10000 lines long) 0 195 33 195 ...

Avoid triggering the pointerenter event when touching and subsequently moving into an element

I am currently working on a React application where I want to enable a user to touch one element and then move to an adjacent element while keeping the touch continuous. The issue I am facing is that the pointerover and pointerenter events only trigger whe ...

What is the best way to regain grid focus following a data reload in ExtJS?

Within my ExtJS view, there is a grid where users can select an entry along with a panel displaying details about the selected row. However, every time a different row is chosen, the view is reloaded causing the grid to lose focus for keyboard navigation. ...

What is the best method for saving HTML form data into a Node JS variable?

I am facing an issue with setting the values of HTML form inputs onto my Node JS variables. In the JavaScript code below, I am struggling to assign values to the variables "hostname" and "port," which should then be concatenated to create a new variable ca ...

The necessary directive controller is missing from the element in the current DOM structure

Can anyone explain the meaning of "required directive controller is not present on the current DOM element"? I encountered this error and would like some clarity. For reference, here is the link to the error: https://docs.angularjs.org/error/$compile/ctr ...

Error message encountered in Rails Webpacker: "Uncaught TypeError: $(...).tooltip is not recognized as a function

I am working on a Rails 6 application where I compile assets using Webpack 4.39.1 with the help of the Webpacker gem. In my webpack configuration file (config/webpack/environment.js), I have included JQuery 3.4.1 and Popper.js as part of the ProvidePlugin ...

The statement "document.getElementById('grand_total_display').innerHTML = "Total is : $"+variable;" is causing issues in Internet Explorer versions 6 and 7

document.getElementById('grand_total_display).innerHTML = "Total is : $"+variable; seems to be causing an error specifically in IE6 and IE7 Within my HTML, I have an element <li> identified as grand_total_display which contains some existing te ...

Utilizing getServerSideProps in the new app router (app/blah/page.tsx) for maximum functionality

I am a beginner in Next.js and I am currently experimenting with the new app router feature by placing my pages under app/.../page.tsx The code snippet provided works when using the page router (pages/blah.tsx) but encounters issues when used in app/blah/ ...

Updating the state of an object within a mapping function

I've been struggling with this issue for two days now. Despite my efforts to find a solution online, I am still stuck and starting to believe that I might be missing something. The main functionality of the app is to click a button and watch an apple ...

set ajax url dynamically according to the selected option value

My form features a select box with three distinct choices <select id="tool" name="tool"> <option value="option1">Option1</option> <option value="option2">Option2</option> <option value="option3">Option3</ ...

Trouble with updating a variable within a loop in Cypress

During my experience with writing Cypress tests, I came across an issue that is preventing me from updating a specific variable. The goal of my test is to run a loop and update the questionId variable within each iteration for making API queries. However, ...

the eventListener is not functioning as expected when used with the 'else' keyword

Everything seems to be working fine until I click on playsong1. The code executes as expected for the first click, but when clicked again, instead of progressing to the conditions after the } else { statement, it re-triggers the same conditions (replayin ...

What sets Import apart from require in TypeScript?

I've been grappling with the nuances between import and require when it comes to using classes/modules from other files. The confusion arises when I try to use require('./config.json') and it works, but import config from './config.json ...

What could be the reason that step 3 of the AngularJS Tutorial is not functioning correctly?

During Step 3 of the AngularJS Tutorial, an additional e2e test is recommended to enhance the example: it('should display the current filter value within an element with id "status"', function() { expect(element('#status').text() ...

Can one intercept the window.location.replace event?

Suppose I am currently browsing the URL "example.com/somepage#somehash" and then decide to execute window.location.hash = "anotherhash", the URL will be updated to "example.com/somepage#anotherhash". This action triggers the window.hashashchange event. On ...

Tips for customizing video layout using HTML

I currently have a basic video displayed on my website <video width="100%" class="posted_vid"> <source src="uploaded_videos/<?php echo $Video; ?>"> </video> However, the video player appears as a default HTML video, simila ...

Storing input data in a JavaScript array instead of sending it through an AJAX request

I've been grappling with this issue for quite some time now, and I just can't seem to wrap my head around it. While there are a few similar solutions out there, none of them address my exact problem. Here's the scenario: I have a form where ...

Utilizing Angular: Filtering Views Based on JSON Data Values

I am struggling to figure out why a basic Angular filter is not working for me in this example. Despite following the recommended format I found online, it does not seem to be functioning properly. Essentially, I just need to display information from the a ...