Filter an array by the property of a separate array

I currently manage two collections - events and bookings. https://i.sstatic.net/c9jAn.png

The Events collection contains various events, while the Bookings collection only includes the eventId of the event that needs to be booked and the user who is currently logged in.

To find events that have not been booked, I utilized lodash:

  const results = _.differenceWith(
          eventsArr,
          bookingArr,
          (event, booking) => event.id == booking.eventId
        );

However, I am struggling to figure out how to select the events that have been booked. I tried filtering the events array based on the eventID from the other array, but it did not work as expected!

If anyone has any suggestions or ideas, they would be greatly appreciated!

EDIT: Including the data structure details here (thank you for the quick responses, providing a complete structure can assist others, especially since the backend is firebase).

The events array

{
  "-LWSkZgZ-e84Aq7EnvOo" : {
    "date" : "January 17",
    "description" : "Lorem ipsum dolor amet fashion axe cray pour-over green juice...",
    "imageUrl" : "https://images.pexels.com/photos/1047940/pexels-photo-1047940.jpeg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=500&w=500",
    "location" : {
      "lat" : 77.88,
      "lng" : 66.65,
      "name" : "Texas CA"
    },
    "name" : "MetalBone",
    "ticketsAvailable" : true
  },
  "-LWSkbMLqDlpTgcgFHy2" : {
    "date" : "January 18",
    "description" : "Mlkshk brooklyn gastropub paleo bicycle rights...",
    "imageUrl" : "https://images.pexels.com/photos/849/people-festival-party-dancing.jpg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=500&w=500",
    "location" : {
      "lat" : 32.77,
      "lng" : 96.7,
      "name" : "Dallas SF"
    },
    "name" : "Big Day Out",
    "ticketsAvailable" : true
  },

The bookings array

{
  "-LWdae8S33xrHfLetvT7" : {
    "eventId" : "-LWSkZgZ-e84Aq7EnvOo",
    "userMail" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95e1f0e6e1d5e1f0e6e1bbf6faf8">[email protected]</a>"
  },
  "-LWdj2UDTwVV6_71Bcyd" : {
    "eventId" : "-LWTraS93uC37S21syqP",
    "userMail" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcc8d9cfc8fcc8d9cfc892dfd3d1">[email protected]</a>"
  }
}

Answer №1

If you're looking to identify common events or bookings based on their ID, you can make use of the _.intersectionWith() function:

const results = _.intersectionWith(
  eventsArr,
  bookingArr,
  (event, booking) => event.id === booking.eventId
);

This code snippet showcases how data is converted to an array and then utilizes _intersectionWith() to identify booked events:

const events = {"-LWSkZgZ-e84Aq7EnvOo":{"date":"January 17","description":"Lorem ipsum dolor amet fashion axe cray pour-over green juice. Salvia everyday carry viral, PBR&B pop-up polaroid direct trade gochujang hot chicken disrupt gentrify quinoa crucifix pabst cred. ","imageUrl":"https://images.pexels.com/photos/1047940/pexels-photo-1047940.jpeg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=500&w=500","location":{"lat":77.88,"lng":66.65,"name":"Texas CA"},"name":"MetalBone","ticketsAvailable":true},"-LWSkbMLqDlpTgcgFHy2":{"date":"January 18","description":"Mlkshk brooklyn gastropub paleo bicycle rights. Man bun brunch helvetica food truck whatever tousled vegan vinyl pug cred mumblecore. ","imageUrl":"https://images.pexels.com/photos/849/people-festival-party-dancing.jpg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=500&w=500","location":{"lat":32.77,"lng":96.7,"name":"Dallas SF"},"name":"Big Day Out","ticketsAvailable":true}}

const bookings = {"-LWdae8S33xrHfLetvT7":{"eventId":"-LWSkZgZ-e84Aq7EnvOo","userMail":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="374352444377435244431954585a">[email protected]</a>"},"-LWdj2UDTwVV6_71Bcyd":{"eventId":"-LWTraS93uC37S21syqP","userMail":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85f1e0f6f1c5f1e0f6f1abe6eae8">[email protected]</a>"}}

const result = _.intersectionWith(
  _.map(events, (v, id) => ({ id, ...v })),
  _.values(bookings),
  (event, booking) => event.id == booking.eventId
)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

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

Creating a 3D card flip effect with CSS that scales the image without sacrificing clarity

Issue I am aware that enlarging a small image using CSS will result in blurriness, but I believe there must be a way to achieve the effect I desire without sacrificing clarity. I suspect that adjusting the initial width/height and transform origins of the ...

Troubleshooting: Difficulty getting CSS `position: absolute` to correctly position a div above all other elements

In my current project, I am utilizing Javascript, specifically the VueJS framework, to create a page named mainTextEditor. This page consists of a text field and a 'popup' that is implemented using a div with a v-if directive to show the div when ...

Get rid of any empty space in the image preview icon

Is there a way to eliminate the white space that appears when mixing landscape and portrait images? I want the images to move up and fill the space, even if they don't align perfectly. Additionally, I would like the images to resize based on the scal ...

Implementing live multiplication feature with input field

I need help with creating a dynamic multiplication feature in a text box. Currently, I have only been able to figure out how to do addition. Please review my JavaScript code below and suggest modifications for implementing multiplication of two values. Se ...

Making changes to the Array.prototype leads to errors in another JavaScript library

I am currently utilizing Crystal Reports within ASP.NET webforms to display some report files. The framework produces javascript for the UI functionality. If I modify the array prototype in any way, the script mentioned above throws 2 errors. These errors ...

Transferring States among Components in ReactJS

Struggling to transfer states between components in my application as the values always end up being undefined. I have a component named Home that captures user input for email and password during login. My goal is to pass these states to another componen ...

Ways to avoid unintentional removal of contenteditable unordered lists in Internet Explorer 10

How can I create a contenteditable ul element on a webpage while avoiding the issue in Internet Explorer 10 where selecting all and deleting removes the ul element from the page? Is there a way to prevent this or detect when it happens in order to insert ...

Ensure that an array in PHP contains a specific set of values

Is there a way to verify that both "ayrshire" and "fife" are included in the $courseAreas array, at the minimum? I attempted the code below, but it did not produce the desired outcome: $courseAreas = array('ayrshire', 'fife', 'ch ...

Information is not readily available through API utilization

For my project, I am implementing a search filter feature. While I can successfully retrieve data by querying the API, no data is displayed when consuming the API on the MVC side. API Controller, [HttpGet("ListExpenseByAccountingSearch/{search}" ...

Using ctypes in Python to call a C function with custom data types

Trying to incorporate existing C code into Python for use on Linux is proving to be a challenge. With limited experience in C, I am currently using ctypes to tackle this issue. The C function I need to call requires a 2D array with custom type entries, and ...

How to increase a bytearray in Python 3?

What is the best way to increment a 16-byte array in Python 3, from 0x00000000000000000000000000000000 to 0x00000000000000000000000000000001? import base64 import Crypto from Crypto.Cipher import AES def incr(): k = b'\x01\x00\x0 ...

Looking up a specific key in a multidimensional array and displaying its value in PHP

Currently, I am attempting to output an array. The code is functioning as expected with a foreach loop. However, I am wondering if it's possible to print the values associated with keys from the array. For instance: key['user_id'] would dis ...

Methods for encoding and decoding special characters using either JavaScript or jQuery

I am looking for a solution to encode and decode various special characters using JavaScript or jQuery... ~!@#$%^&*()_+|}{:"?><,./';[]\=-` I attempted to encode them using the following code snippet... var cT = encodeURI(oM); // ...

Minimum space required for Array Subset problem with time complexity of O(n)

I'm looking to create a Java function that compares two arrays and returns true if the smaller array is a subset of the larger array. Is there a more concise and space-efficient way to implement the code below while maintaining O(n) time complexity? ...

Identify the label of the SAS variable and subsequently modify its value

Hey there! I'm facing a bit of a challenge and could use some assistance. So, I've got this dataset with around 300 variables, most of which are numeric. The data comes from an Excel sheet. Now, about 100 of these variables in the spreadsheet a ...

Encountering a memory storage problem when trying to include additional images to create a word document using the docx node

const imageResponse = await axios.get(url[0], { responseType: "arraybuffer", }); const buffer = Buffer.from(imageResponse.data, "utf-8"); const image = Media.addImage(doc, buffer); Within a loop that runs 1 ...

Discovering identical objects by property and combining them with the help of JavaScript or UnderscoreJS

Below is an array that I have: var somevalue = [{ code: 1, name: 'a1' }, { code: 2, name: 'b1' }, { code: 1, name: 'a2' }, { code: 1, name: 'a3' }, { code: 2, name ...

Improve performance by prefiltering Angular $http requests, similar to the way I demonstrated

For CSRF protection, I have set up an ajax prefilter that utilizes the MVC @Html.AntiForgeryToken() and automatically adds it to every .ajax request. $.ajaxPrefilter(function (options, originalOptions, jqXHR) { if (options.type.toUpperCase() = ...

Strange response received from $http GET request on Android device running Crosswalk

I am attempting to retrieve data in JSON format from an API using AngularJS. The process is successful on iOS and desktop browsers, but I'm encountering a strange response when trying it on my Android device. The request code looks like this: $http({ ...

How to Retrieve a Value Associated with a Key in a JavaScript Array of Objects

I've exhausted multiple attempts to solve this issue, but unfortunately, I can't seem to get it right. Here's the problem at hand: In my JavaScript code, I have an array of objects structured like this: var myArrOfObjs = []; var myObject1 ...