Searching for information in one array using a loop with another array (MongoDB and JavaScript)

I have two arrays that need to be compared for matching elements.

let firstArray = [1, 2, 3]
let secondArray = [{id:1}, {id:1}, {id:3}]

I am trying to create a new array containing objects with the same id.

Despite trying different approaches, I am unable to achieve the desired outcome.

Update:

After receiving helpful input from flyingfox, I realized that my current solution does not account for duplicate values in the arrays. For example:

let firstArray = [1, 3, 3, 3]
let secondArray = [{id:1}, {id:2},{id:3}]

firstArray = firstArray.filter(item1 => secondArray.some(item2 => item2.id === item1))
secondArray = secondArray.filter(item1 => firstArray.some(item2 => item2 === item1.id))

Currently, the secondArray only contains [{id:1}, {id:3}], but I need to include duplicates as well. 
The desired output for secondArray should be [{id:1}, {id:3}, {id:3}, {id:3}] since 3 appears multiple times in the firstArray.

Answer №1

If you're looking to gather all elements with the same id into a new array, the code snippet below can serve as a helpful guide:

let array1 = [1, 2, 3]
let array2 = [{id:1}, {id:1}, {id:3},{id:4}]

array1 = array1.filter(e1 => array2.some(e2 => e2.id === e1))
array2 = array2.filter(e1 => array1.some(e2 => e2 === e1.id))

let array3 = [...array1,...array2]
console.log(array3)

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

Having trouble rendering a dynamic table with JavaScript utilizing a JSON object

I am struggling to retrieve data in JSON format and display it in a table. Despite trying various methods, I have been unable to make it work. Below is the code for this function. Can someone please assist me in identifying what is wrong with it? As of now ...

Get the sum of items in a assortment

Is there a way to convert the command db.collection.count() into a Python script that simply returns a number? # Importing a JSON file into MongoDB logger.info('Importing the .json file into MongoDB database') # subprocess.call('mongoimport ...

Error Encountered: "JSON Post Failure in ASP.net MVC resulting in 500

Whenever I attempt to send a variable to JSON on ASP.net MVC, I encounter the following error: jquery-2.2.3.min.js:4 GET http://localhost:58525/Order/GetAddress/?userid=42&email=asandtsale%40gmail.com 500 (Internal Server Error) This is my controller ...

URL validation RegEx in AngularJs using Javascript

I am looking for the following URLs to return as true other.some.url some.url some.url/page/1 The following URL should be flagged as false somerandomvalue Here is the regex I have been experimenting with so far: /^(?:http(s)?:\/\/) ...

Tips on updating a child object in the state using a reducer with Redux

I am facing a challenge with modifying elements inside an object within my state. Currently, I am able to modify elements at the first level, such as the step property. However, I am seeking a solution to modify elements within an object nested inside my s ...

Can you explain the ratio between 1 unit in Three.js and 1 unit in Oimo.js?

When using Three.js to create objects and combining it with a physics system like oimo.js, I've noticed that each system has its own sizing method. While Three.js has its own sizing system for object creation, oimo.js uses a different sizing system sp ...

What is the best way to notify a user if the number they input into a one-dimensional array has already been used?

I am currently working on a program that requires the user to input 5 distinct numbers into a 6-element one-dimensional array. These numbers need to be between 1 and 69, and must not already exist in the array. While I have successfully implemented a chec ...

Unrecognized files located within the same directory

My main.html file located in the templates folder also contains three additional files: date.js, daterangepicker.js, and daterangepicker.css. Despite including them in the head of the HTML as shown below: <script type="text/javascript" src="date.js"> ...

Loop through the last modified file

I am currently working on a webpage that displays the "last-modified" date of each file it loads: Have you noticed how the dates are loaded one by one as the page makes calls to the header? If not, try hitting F5 to refresh the page. Is there a way to im ...

Is it possible to assign a class or id to a dynamically inserted link using JavaScript?

Currently, I have code that effectively inserts a link to the selected text: document.execCommand('CreateLink', false, 'link.com') Although this method works well, I am eager to include a class/id for the link to simplify styling it w ...

Transitioning effect when tapping a link that guides you to a different section of the webpage

Just by reading the title, you can understand my concern. Currently, when I click on "Example 4", the page abruptly scrolls to the h1 of Example 4. It looks so ungraceful, like a sudden boom. I would prefer a smooth scrolling effect. Is it possible to achi ...

Filtering out any inappropriate characters from the XML data before processing it with the XMLSerializer function

I am currently working on a solution to store user-input in an XML document using client-side JavaScript and then transmit it to the server for persistence. One specific issue that I encountered was when a user input text containing an STX character (0x2) ...

Emulating Data in Angular 2 Using Configuration Similar to Ember Mirage

Is there a way to mock data through configuration in Angular 2 similar to how it's done in Ember Mirage? I'm aware that I can create my own solution using Dependency Injection and MockBackend to intercept HTTP calls and provide dummy data. Howeve ...

Using Three.js to create a distorted texture video effect

Check out the example linked here for reference: In this particular project, there are two cylinders involved - an outer cylinder with an image texture and an inner cylinder with a video texture. Once the second cylinder is created and added to the scene, ...

Having trouble with WebRTC video streaming on Firefox?

I have implemented one-way broadcasting in my Dot Net MVC website for video streaming using the example found at https://github.com/muaz-khan/WebRTC-Experiment/blob/master/webrtc-broadcasting/index.html. While it works perfectly in Google Chrome, unfortuna ...

Automatically send users to the login page upon page load if they are not authenticated using Nuxt and Firebase

I'm currently facing an issue with setting up navigation guards in my Nuxt application. The goal is to redirect users to the login screen if they are not authenticated using Firebase Authentication. While the router middleware successfully redirects u ...

How can one create a function that delays the execution of code until AJAX data is received

I developed a CKEditor plugin that fetches data via ajax to create RichCombo functionality. The plugin functions correctly, however, when there are multiple instances of the editor on a single page, each plugin ends up sending its own ajax request, leading ...

Extracting information from a JSON data within an API

How can I retrieve data with a name tag from JSON data using Ajax? The function showCard is not functioning properly when I try to grab data with a name tag. My goal is to display the name of the API data when an img element with the class found is clicked ...

Ways to emphasize an HTML element when clicked with the mouse

Can JavaScript be used to create code that highlights the borders of the HTML element where the mouse pointer is placed or clicked, similar to Firebug, but without needing a browser extension and solely relying on JavaScript? If this is possible, how can ...

Verify the front-end application and authenticate the backend REST API

My project involves developing a REST API and application logic on the client-side, keeping them separate and independent of each other. Now I am looking to implement an authentication system that will automatically authenticate users both on the client-si ...