Tips on obtaining a unique value that does not already exist in a specific property within an Array of objects

I am faced with a challenge involving an array that contains objects with both source and target properties. My goal is to identify a value that never appears as a target.

My current approach seems convoluted. I separate the elements of the array into two new arrays, all containing all elements and targets containing just target elements. Then, I apply a filter to find the desired value.

    const a = [
      { source: '2', target: '3' },
      { source: '1', target: '2' },
      { source: '3', target: '4' },
      { source: '4', target: '5' }
    ];

    const all = ['1', '2', '3', '4', '5'];
    const targets = ['3', '2', '4', '5'];
    console.log(all.filter(e => !targets.includes(e))[0]);

I am seeking a more efficient solution that does not require creating these intermediate arrays, as I know the returned element will be unique. Thus, I prefer to receive a single value instead of an array as the answer.

Answer №1

To locate the first matching element, you can utilize the .find method:

const a = [
  { source: '2', target: '3' },
  { source: '1', target: '2' },
  { source: '3', target: '4' },
  { source: '4', target: '5' }
];
const sources = [];
const targets = [];
a.forEach(({ source, target }) => {
  sources.push(source);
  targets.push(target);
});

console.log(sources.find(e => !targets.includes(e)));

If optimizing for performance is crucial, consider using a Set instead of an array for the targets variable. This allows you to employ the .has method instead of .includes, resulting in an overall time complexity of O(n) rather than O(n^2):

const a = [
  { source: '2', target: '3' },
  { source: '1', target: '2' },
  { source: '3', target: '4' },
  { source: '4', target: '5' }
];
const sources = [];
const targets = new Set();
a.forEach(({ source, target }) => {
  sources.push(source);
  targets.add(target);
});

console.log(sources.find(e => !targets.has(e)));

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

How to filter dependency-injected asynchronous data based on conditions?

I have developed a NodeJS application that utilizes dependency injection. One of the key features of the app is that it can execute multiple functions (modules) simultaneously, and if multiple modules request data from the same async resource, the app ensu ...

Axios fails to capture and transmit data to the client's end

I created a backend using Express to retrieve Instagram feed images and then send their URLs to my front end, which is built with ReactJs. When I fetch the image URLs with instagram-node and send them to the front end, everything functions as expected. How ...

What could be the reason behind my Javascript code returning "object object"?

I am a beginner with jQuery. I attempted to calculate the sum of items from my django views using jQuery. Here's what I have so far: $(document).ready(function() { var sch = $('#sch-books'); var gov = $('#gov-books'); ...

Typing the url in the address bar when using Angular's ui-router

Two distinct states are present: .state('test', { url: '/test', templateUrl: 'js/angular/views/test.html', controller: 'UserController', }) .state('test.list', { url: ' ...

NuxtJs: Oops! It looks like NuxtError is not defined in this context

Exploring NuxtJs is new to me. I decided to experiment with how nuxt-link functions by purposely setting up a nuxt-link to a non-existent route in order to trigger the default 404 page. Here's the line of code I added to the pages/index.vue file: < ...

Can a Vue application be made type-safe without the need for transpilation?

Is it possible for Vue to be type-safe when used without transpilation (without a build step) as well? Can TypeScript or Flow be used to ensure type safety? ...

Integrate data from Firebase into a React-Table component

I am currently working on a table component that fetches data from Firebase to populate three fields: Name Date Comment For each entry, I want to add a new row. The pivot has been successfully added. However, when trying to populate the table, I am encou ...

Angular $compile encountering issues when attempting to compile a string containing non-HTML characters

I am faced with a challenge of utilizing $compile to insert HTML content provided by a user into a directive. module.directive('foo', ["$compile", function($compile) { return { // ... link: function($scope, el) { ...

Tips for displaying a gallery of 5 images in a 2-row slider using bxslider

I've been attempting to create a unique image slider using bxslider. My goal is to have a 2-row slider with 5 images displayed in each row. However, I'm encountering difficulties when I try to integrate the HTML, CSS, and JavaScript code. Despit ...

If the browser closes and there is no recipient to receive the data requested by my ajax, what ultimately becomes of that data?

On my website, utilizing vb.net / c# programming, there is javascript ajax code that retrieves data from the database and sends JSON back to the page. If, just before the ajax call is able to receive the JSON, the browser is closed or the page is redirect ...

Creating a GWT-compatible solution for implementing the Google Visualization - Annotation Chart

I am currently using the newly launched Annotation Chart in GWT by integrating native JavaScript. I have managed to display the example chart successfully, but unfortunately, it lacks interactivity and behaves more like an image. Can anyone provide guidanc ...

Safari experiences occasional failures with pre-signed post uploads to S3 when using multipart/form-data for file uploads

Lately, I've encountered issues with pre-signed post uploads to S3 that seem to be unique to Mobile Safari browsers. Interestingly, the error has also shown up occasionally on Desktop Safari. Whenever this error occurs, it triggers a response from S3 ...

Determine whether an element has the capability to hold text content

Is there a surefire and reliable method to determine if an HTML element is capable of holding text, using only pure JavaScript or jQuery? For example, <br>, <hr>, or <tr> cannot contain text nodes, whereas <div>, <td>, or < ...

Unable to retrieve DateTime.Now as a string within a Razor view

I am trying to retrieve the current time in a Razor View and utilize it in JavaScript, as demonstrated below: @{ string fileName = "Score_List_" + DateTime.Now.ToShortDateString(); } <script> // assigning C# variable to JavaScript variabl ...

Vue.js throws an error because it is unable to access the "title" property of an undefined value

I am currently facing an error and unable to find a solution. Even after changing the title to 'title', the error persists. methods.vue: <template> <div> <h1>we may include some data here, with data number {{ counter ...

Troubleshooting the Create Order Issue: Integrating PayPal Checkout with Smart Payment Buttons using React and Redux

Every time I attempt to process a payment, I encounter a 422 error: Unprocessable entity. The issue arises when I try to dynamically capture the purchased item details received from the redux store. I tried following this example (duplicate): PayPal Check ...

Angular 2's Implementation of Hierarchical Dependency Injection

I'm encountering a problem with my Angular 2 application. I have a root component, AppComponent, where I've injected a service called ProductService. Now, I am trying to resolve this service in one of the child components, ProductList, but I keep ...

Retrieving various pieces of data in Express

After scouring through various websites, I am still unclear on how to extract multiple GET variables using Express. My goal is to send a request to a Node.JS Express server by pinging the URL with: file_get_contents('http://127.0.0.1:5012/variable1/v ...

How can I receive live notifications for a document as soon as it is created?

My Angular app is connected to Cloud Firestore, and I've created a function in a service to retrieve a user's rating from the 'ratings' collection. Each rating is stored in this collection with the document ID being a combination of the ...

Adjust the position of an element based on changes in window size using jQuery

Wondering if this question is unique, as I've spent quite some time searching for a solution to this issue without any luck. Perhaps my search criteria aren't correct. I have a navigation bar that becomes fixed when it reaches the top of the vie ...