A guide on sorting an array based on elements from a different array

We are currently in the process of developing an application using Vue and Vuex. Our goal is to display a list of titles for venues that a user is following, based on an array of venue IDs.

For instance:

venues: [
{venue:1, title: Shoreline}
{venue:2, title: Bill Graham}
{venue:3, title: Golden Gate}
{venue:4, title: Orphium}
]

My current list of followed venues includes: [1, 3]

However, I don't want to simply show the IDs 1 and 3. Instead, I want to display "Shoreline" and "Golden Gate" as the followed venues.

I have been attempting to utilize map and filter functions without success.

getFollowingState({ commit, state }) {
  fb.venueFollowersCollection.where("user", "==", state.currentUser.uid).onSnapshot(querySnapshot => {
    let followingArray = []
    querySnapshot.forEach(doc => {
      console.log(doc.data())
      let followed = doc.data().venue
      followingArray.push(followed)
    })
    store.dispatch('getUserVenues', followingArray)
    commit('setFollowedVenues', followingArray)
  })
},

The above code fetches an array of venue IDs that I am following. Here is an example snapshot of doc.data():

email: "greg@..."
name: "Gre..."
phone: "925..."
user: "jxckuJwXxRdgfKmEduYlLbfxd1g1"
venue: "S2XWn8tG0tIMyoOyAcuc"
venueName: "California Memorial Stadium"

Next, my objective is to retrieve each venue object where the ID matches one of the IDs of venues I am following (payload).

getUserVenues({ commit }, payload) {
  fb.venuesCollection.onSnapshot(querySnapshot => {
    let venuesArray = []
    querySnapshot.forEach(doc => {        
      if ((doc.data()).includes(payload)) {
        let venue = doc.data()
        venuesArray.push(venue)
        console.log(doc.data())
      }
    })
    console.log(venuesArray)
    commit("setUserVenues", venuesArray)
  })
},

A challenge arises here because "payload" is not recognized as a string. What adjustments should be made in order to achieve the desired outcome?

Answer №1

A convenient method to filter an array by elements from another array is by utilizing the includes() function:

const locations = [
{location:1, name: 'Beachfront'},
{location:2, name: 'City Center'},
{location:3, name: 'Mountain View'},
{location:4, name: 'Lakeside'}
];

const selectedLocations = [1, 3];

const names = locations
  .filter(item => selectedLocations.includes(item.location))
  .map(item => item.name);

console.log(names);

Output:

[ 'Beachfront', 'Mountain View' ]

Answer №2

It seems like the code you are looking for is something along these lines:

getUserVenues({ commit }, payload) {
  fb.venuesCollection.onSnapshot(querySnapshot => {
    const venuesArray = [];
    querySnapshot.forEach(doc => {
      const venue = doc.data();
      if (payload.includes(venue.venue)) {
        venuesArray.push(venue);
      }
    });
    commit('setUserVenues', venuesArray);
  });
},

You may find the variables a bit confusing because your venue object includes a venue field, rather than an id. Assuming that you are trying to match the id with venue.venue in the payload, using payload.includes should serve your purpose.

If you wish to commit only specific data from the venue object, you can try the following options:

Committing only the names:

commit('setUserVenues', venuesArray.map(v => v.venueName));

Committing both names and ids:

commit('setUserVenues', venuesArray.map(v => ({ id: v.venue, title: v.venueName})));

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

Detecting Collisions in a Canvas-Based Game

As part of my educational project, I am developing a basic shooter game using HTML5 canvas. The objective of the game is to move left and right while shooting with the spacebar key. When the bullets are fired, they travel upwards, and the enemy moves downw ...

Error: Attempting to access the 'clipboard' property on an undefined object results in a TypeError when invoking this.$q.electron.clipboard

I'm currently working on incorporating copy to clipboard functionality into my app using Electron. This is the command I am using: methods: { copyToClipboard () { if (process.env.MODE === 'electron') { this.$q.electro ...

The art of Vue JS displaying content

Learning how to make API requests using axios has greatly improved my ability to retrieve data in a client-side container and display it in my component template. It's been quite effective so far. Having worked with twig before, I can't help ...

When the mouse hovers over the slider, the final image jumps into view

After successfully building an image slider that displays 2 partial images and 1 full image on hover, I encountered a bug when setting the last image to its full width by default. This caused a temporary gap in the slider as the other images were hovered o ...

Concealing overflow in a sticky container when a fixed child element is present

I am currently working on a website where I have implemented slide-up section panels using position: sticky while scrolling. However, I am encountering issues with fixed elements within the sticky panels not properly hiding outside of the respective sectio ...

Transferring information from Child to Parent using pure Javascript in VueJS

I am familiar with using $emit to pass data from child components to parent components in VueJS, but I am trying to retrieve that value in a JavaScript function. Here is my situation: Parent Component created () { this.$on('getValue', func ...

Upon running `vue create project`, an error with code EINTEGRITY was encountered in npm

Every time I try to create a new project with vue create project, I encounter the following error: npm ERR! code EINTEGRITY npm ERR! Verification failed while extracting node-notifier@^5.4.2: npm ERR! Verification failed while extracting node-notifier@^5.4 ...

A comprehensive guide on making an AJAX call to a self-hosted servlet

I created a servlet in Eclipse IDE for Java EE that posts data as an XML page and hosted it on a Tomcat server. The servlet can be accessed at http://localhost:8080/Checkers/CheckersServlet. When I open this URL in Firefox, the XML loads correctly. Now, I& ...

Combine several items to form a single entity

When I have two objects returned from the database, my goal is to combine them into one object. Here are the examples: { "id": 4, "first_name": "s", "last_name": "a", ...

Ways to resolve the error "Expected an assignment or function call but found an expression with no-unused-expressions"

Issue : Error in ./src/components/main.js Line 7: No function call or assignment found, only an expression is present (no-unused-expressions) Search for the specific keywords to get more information on each error. import React from 'react'; ...

Using AngularJS to transfer data from a datepicker to an ng-model

I am currently trying to figure out how to pass the date from a datetimepicker into the model. Unfortunately, I am facing some challenges with this process. I wish I could provide a demo of the issue on a fiddle, but I am unsure of how to do so due to the ...

tips for successfully transferring date and time data between json and nosql databases like firestore

Input: Created_At:Monday, 29 April 2019 15:07:59 GMT+05:30 Updated_At:Monday, 29 April 2019 15:07:59 GMT+05:30 I attempted to export data in JSON format from Firestore using the npm package firestore-export-import. However, the output I received was: ...

AngularJS - Issue: [ng:areq] The 'fn' argument provided is not a function, instead it is a string

I encountered an issue: Error: [ng:areq] Argument 'fn' is not a function, received string Despite following the recommendations of others, I still have not been able to resolve the problem. Below is the code snippet in question: controller. ...

Using the ng-repeat directive along with the string replace expression allows for dynamically

Struggling to find a way to remove a substring within an angular expression while using the ng-repeat directive. The controller resides in an external JavaScript file, and here is the corresponding HTML code snippet. function myController($scope, $http ...

Incorporating CouchDB storage into a Node.js socket.io JSON data stream

Currently in the process of researching how to implement persistence for a real-time Twitter JSON feed in Node.js. The stream is set up and sending data to the client, but I'm struggling with storing this information in a CouchDB database so that it c ...

"Clicking on the hamburger menu causes the webpage to reset its scroll

I recently integrated a mobile hamburger menu into my website, which is primarily built around a single page. However, I noticed that whenever I open the menu, it automatically scrolls to the top of the page regardless of where you were previously scrollin ...

Toggle the visibility of a div depending on the user's selection

My HTML select element has a few options to choose from: <select class="form-control" data-val="true" data-val-number="The field CodeSetup must be a number." id="CodeSetup" name="CodeSetup"> <option selected="selected" value="0">AllCodes< ...

Clipped Words & Silhouettes

I'm having trouble ensuring the text in this particular example displays correctly. I am experiencing challenges with the clipping of text and shadows on certain letters, and I'm struggling to identify the root cause as well as the solution. In ...

Structural directive fails to trigger event emission to parent component

Following up on the question posed here: Emit event from Directive to Parent element: Angular2 It appears that when a structural directive emits an event, the parent component does not receive it. @Directive({ selector: '[appWidget]' }) export ...

Tips for displaying all documents within a MongoDB collection using the sharedb-cli command line tool

My client-demo is not working as expected. I am trying to retrieve all documents from the "file" collection, but I am getting null results. https://i.sstatic.net/Pw6sA.png When testing with the mongo shell, I can see that the document data actually exist ...